如何居中和重叠DIV

时间:2017-02-14 22:21:40

标签: html css

我有2个DIV,我想要居中并重叠。较小的一个是放在较大的一个上面。

它在全屏幕上效果很好,但如果我减小浏览器尺寸,则顶部/小部分会向左移动。



<div style="position: relative; top: 160px; border: thin solid gray; border-radius: 10px; width: 300px; height: 64px; margin-left: auto; margin-right: auto; z-index: 1; background: url(...); background-repeat:no-repeat; background-position:top; background-color: #4b2f84">&nbsp;</div>
<div style="position: absolute; top: 200px; left: 15%; width: 70%; background: white; border: thin solid gray; border-radius: 10px; height: 500px; padding: 50px 30px; margin: auto">something
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

在尝试居中和重叠内容时,我喜欢将left: 50%;transform: translateX(-50%);结合使用。

内容向左偏移50%,然后向左偏移-50%..或(this.left == parent.x + parent.width* 0.5 - this.width*0.5)

#div1 {
  position: relative;
  top: 160px;
  border: thin solid gray;
  border-radius: 10px;
  width: 300px;
  height: 64px;
  margin-left: auto;
  margin-right: auto;
  z-index: 1;
  background: url(...);
  background-repeat: no-repeat;
  background-position: top;
  background-color: #4b2f84
}
#div2 {
  position: absolute;
  top: 200px;
  left: 50%;
  transform: translateX(-50%);
  width: 70%;
  background: white;
  border: thin solid gray;
  border-radius: 10px;
  height: 500px;
  padding: 50px 30px;
  margin: auto
}
<div id="div1">&nbsp;</div>
<div id="div2">something</div>

相关问题