我正在尝试将一个 div(包含搜索栏)垂直居中放置在另一个(顶部横幅)中。我的印象是要这样做你做了以下事情:
#banner {
height: 35px;
width: 100%;
}
#searchbar {
height: 15px;
position: relative;
top: 50%;
margin-top: -7.5px; /* half of the height */
}
在您添加 margin-top
之前,这一切正常,此时它也应用于 #banner
。
是否有其他方法可以做到这一点,还是我只是做错了?
最佳答案
我使用 line-height
,其值与父 div 的高度相同。
如下所示:http://jsfiddle.net/vkJ78/24/
CSS:
#banner {
background-color: #770E17;
height: 35px;
width: 100%;
border-bottom: 1px solid #333;
}
#src {
width: 300px;
height: 15px;
border: 1px solid #333;
padding: 3px;
}
#srcdiv {
width: 308px;
margin: 0px auto;
position: relative;
line-height: 35px;
}
编辑:根据 NGLN 的建议,这也将修复水平居中,#srcdiv
和 #src
具有相同的宽度。
关于css - 嵌套div垂直对齐问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6863710/