html - 垂直居中两个重叠的div

标签 html css mobile

我正在开发我的网站的移动版本,我在垂直居中两个 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/

相关文章:

jquery - 更改动画 Sprite 表时 HTML5 Canvas 挂起(逐帧视频播放)

javascript - 如何使用javascript将视频文件转换为字符串?

html - 如何拉伸(stretch)菜单中的元素(从右到左)- HTML 和 CSS

javascript - 当我的响应式菜单打开时,如何删除用户转到两侧的功能?

html - 在导航栏 Bootstrap 中对齐控件

asp.net - 移动网络开发?

html - 悬停时更改背景颜色

html - 如何使图像占据屏幕的整个宽度? (HTML,CSS)

javascript - Jquery Accordion 上的图标更改

mobile - LabVIEW - 移动应用程序