动态居中一个div在另一个div上方

14

我想要将一个没有固定宽度的 div 居中放置在视频上面,所以如果浏览器窗口大小改变,这个 div 也会跟着缩小但是始终保持在中心位置。目前我使用的方法是通过设置 left:50% 并使用负边距来实现,但问题显然是由于负边距是固定的,所以会向左移动。有什么好的办法吗?谢谢!

我的 HTML 代码:

<div id = 'top-container'>
   <video id='top-vid' autoplay loop width=100% height='auto' class='no-mobile'>
       <source src='DS_Intro.mov' type='video/mp4'>
       <source src='test.webm' type='video/webm'>
   </video>

   <div id = 'top-content'>
       <div id = 'top-text'>
           <div id = 'top-img'>
               <img src='ds_white.png' width = "100%" height = 'auto'>
           </div>
           <h1 id = 'top-slogan'>a boutique video production studio</h1>
       </div>
   </div>
</div>

我的CSS:

#top-container{
    width:100%;
    height:100%;
}

#top-content{
    max-width:1200px;
    margin-right:auto;
    margin-left:auto;
}

#top-img{
    width:100%;
    padding-bottom: 10%;
}

#top-slogan{
    text-align:center;
    padding-bottom:10%;
    font-weight: 100;
    color:#5DBCD2;

}

#top-text {
    top: 50%;
    left: 50%;
    margin-left: -360px;
    position:absolute;
    width:50%;

}

这里是FIDDLE


在你的#top-text规则中尝试使用margin: 50% auto 0; - Ben Harold
1个回答

23

使用 transform: translate(-50%, -50%) 可以实现此功能,通过使用这个方法,内部元素可以是动态的(不需要负边距),请参见此示例

http://jsfiddle.net/Mfsfm/2/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接