将DIV保持在其父DIV的底部中心

Sam*_*pta 7 html css

我的HTML结构基本上是这样的 -

<div id="header">
    <div class="container">
    </div>
</div>
<div id="content">
    <div class="container">
    </div>
</div>
<div id="footer">
    <div class="container">
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

忽略任何元素,除了<div id="header"> 我想在正确的底部中心对齐<div class="container">内部<div id="header">.我正在使用以下CSS代码 -

#header{ width:1062px; height:326px; background-color:#110000; text-align:center; position:relative; }
#header .container{ width:940px; height:262px; background-color:#220000; margin:0px auto; position:absolute; bottom:0px; }
Run Code Online (Sandbox Code Playgroud)

父(#header)和子(#header .container)DIV之间存在高度差异.position:absolute;从儿童中心移除它但它粘在父母的顶部而不是底部.将position:absolute;它粘在底部但是将它对齐到左边.

如何同时对齐中心底部

Kam*_*ior 12

我尝试了上面的所有解决方案但是当你调整浏览器窗口大小时它没有用.当您不知道元素的宽度时,主要应用此解决方案.或者如果在调整大小时更改宽度.

经过一些研究后,我尝试了以下内容,它在所有屏幕尺寸上都能很好地工作.

#somelement {
  position: absolute;
  left: 50%;
  bottom: 0px;
  -webkit-transform: translateX(-50%);
  transform: translateX(-50%)
}
Run Code Online (Sandbox Code Playgroud)

我为仍然面临这个问题的人分享了这个.

  • 这需要得到更多的支持!在我的设置上完美运行! (3认同)

fca*_*ran 5

以这种方式尝试:

#header .container{ 
   width: 940px;  
   height: 262px; 
   background-color: #220000; 
   position: absolute;
   bottom: 0 ;
   left: 50%;
   margin-left: -470px; 
}
Run Code Online (Sandbox Code Playgroud)