我正在开发我的网站的移动版本,我在垂直居中两个 div 时遇到了问题。由于它是一个移动网站,我的 CSS 需要在任何类型的屏幕分辨率下工作,所以这就是我遇到问题的地方。此外,根据您所在的页面,将使用不同的图像,因此图像的分辨率也不是静态的。我需要一种方法使我的图像 div 和文本 div 居中,无论它们的高度或宽度如何。
我做了一个 fiddle从这里开始。如您所见,我选择绿色区域
作为手机的“屏幕”,我希望图片垂直居中,文字位于图片上方并垂直居中以及。有帮助吗?
到目前为止我所拥有的...(在我的 jsfiddle 中)
HTML:
<div id = "screen">
<div class = "overlay" id = "picture"><img src = "http://www.startingtofeelit.com/wp-content/uploads/2013/10/Tennis-Mean-Streets.jpg" /></div>
<div class = "overlay" id = "text">This is where the text would appear</div>
CSS:
#screen {
width:360px;
height:640px;
background-color:#0f0;
position:relative;
overflow:hidden;
display:table-cell;
vertical-align:middle;
}
.overlay {
position:absolute;
top:0;
left:0;
}
#picture {
}
#picture img{
width:100%;
}
#text {
background-color:#000;
width:100%;
opacity:0.5;
color:#fff;
}
最佳答案
对于垂直居中,您可以将边距顶部/底部设置为自动。 如果我明白你想要文本的位置,这应该可行。
HTML
<div id = "screen">
<div class = "overlay" id = "text">This is where the text would appear</div>
<div class = "overlay" id = "picture"><img src = "http://www.startingtofeelit.com/wp-content/uploads/2013/10/Tennis-Mean-Streets.jpg" /></div>
</div>
和CSS
#screen {
width:360px;
height:640px;
background-color:#0f0;
position:relative;
overflow:hidden;
display:table-cell;
vertical-align:middle;
}
#picture {
margin: 0 auto;
}
#picture img{
width:100%;
}
#text {
position: absolute;
top:50%;
background-color:#000;
width:100%;
opacity:0.5;
color:#fff;
}
关于html - 垂直居中两个重叠的div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20080175/