【问题标题】:How to center and overlap DIVs如何使 DIV 居中和重叠
【发布时间】:2017-02-15 06:26:27
【问题描述】:

我有 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>

【问题讨论】:

标签: html css


【解决方案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>

【讨论】:

    猜你喜欢
    • 2018-03-13
    • 2017-11-21
    • 2013-02-27
    • 2019-07-13
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    • 2014-02-15
    • 1970-01-01
    相关资源
    最近更新 更多