我正在使用一组 HTML 模板,这使得要完全按照我想要的方式自定义有点棘手。所以我坚持使用一种缺乏灵 active 的结构。
我有一个占页面宽度 50% 的 div,但我想在页面中间居中放置一个包含的 div。由于页面其他部分的其他限制,我真的无法更改设置为position: relative 的parent div。
这是我想要的效果:
这是我目前的代码(无法正常工作):
HTML:
<div class="parent">
<div class="centerpage"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/3/3f/Berlin_U-Bahn_Train_A3L71.jpg/220px-Berlin_U-Bahn_Train_A3L71.jpg"></div>
</div>
CSS:
.parent {
background-color: #85D782;
height: 400px;
width: 50%;
position: relative;
}
.centerpage {
position: absolute;
}
最佳答案
您可以使用绝对和负边距的旧方法: http://codepen.io/anon/pen/Htpen
.parent {
background-color: #85D782;
height: 400px;
width: 50%;
position:relative;
}
.centerpage {
position: absolute;
left:100%;
top:50%;
vertical-align:middle;
margin :-80px 0 0 -110px;/* negative margin is equal to half height/width of image */
}
或使用背景图像或渐变 http://codepen.io/anon/pen/GDbtg :
.centerpage {
background:
linear-gradient(to right,
#85D782 0%,
#85D782 50%,
#ffffff 50%,
#ffffff
)
;
height: 400px;
text-align:center;
line-height:400px;
}
img{
display:inline-block;
vertical-align:middle;
}
关于css - 当 div 被限制为偏离中心的有限宽度 div 时,它在页面上水平居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21220086/