html - 在相对元素内水平居中绝对元素

标签 html css

我无法将 position: relative 元素 ( https://jsfiddle.net/qL0c8cau/ ) 中的内部 position: absolute 元素居中:

html,body,div {margin:0;padding:0;}
.one {
  position: relative;
  margin: 50px auto;
  width: 200px;
  height: 100px;
  background: #900;
}
.two {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  margin: auto;
  background: #0f0;
  opacity: 0.3;
  height: 160px;
  width: 400px;
}
<div class="one">
  
  <div class="two"></div>
  
</div>

我看不出有什么问题。我设置的一切都是正确的,但由于某种原因它没有水平对齐。

我在这里做错了什么?

最佳答案

将此添加到您的 CSS 中

.two {
  position: absolute;
  top:50%;
  left: 50%;
  transform:translate(-50%,-50%);
  margin: auto;
  background: #0f0;
  opacity: 0.3;
  height: 160px;
  width: 400px;
}

此代码将确保,无论您的容器有多大,内部容器始终位于外部容器的中心。

html,body,div {margin:0;padding:0;}
.one {
  position: relative;
  margin: 50px auto;
  width: 200px;
  height: 100px;
  background: #900;
}
.two {
  position: absolute;
  top:50%;  /* this to center the box w.r.t to parent */
  left: 50%;/* this to center the box w.r.t to parent */
  /* Above 2 lines wont fully center it, the next line internally centers it, buy moving itself 50% left and top */
  transform:translate(-50%,-50%);
  margin: auto;
  background: #0f0;
  opacity: 0.3;
  height: 160px;
  width: 400px;
}
<div class="one">
  <div class="two"></div>
</div>

关于html - 在相对元素内水平居中绝对元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50065698/

相关文章:

html - 如何将超棒的字体图标对齐到中心?

javascript - 在 Chrome 扩展中插入图像?

html - Photoshop px 大小与 CSS px 大小不同

jquery - 使用 jquery 使 div 在容器内移动(就像幻灯片放映一样)

html - 将 div 放置在图像的 Angular 落

html - 如何使用 HTML 创建层次结构

Jquery 追加悬停 css 样式

css - FF帮助中的自动换行/换行?

javascript - 简单的 jquery 幻灯片修复我无法弄清楚

html - 嵌套的 CSS 下拉菜单