当页面被约束到偏心的有限宽度div时,在页面上水平居中div

时间:2014-01-19 17:26:50

标签: css

我正在使用一个设置的HTML模板,这使得按照我想要的方式进行自定义变得有点棘手。所以我坚持使用一种缺乏灵活性的结构。

我有一个占据页面宽度50%的div,但我想在页面中间放置一个包含div的中心。由于页面其他部分的其他限制,我实际上无法将父div设置为 position:relative

这就是我追求的效果: enter image description here

这是我到目前为止的代码(不起作用):

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;
}

2 个答案:

答案 0 :(得分:1)

put image into a div and apply class below 

{
width: 100px /* with your width whatever it is */;
text-align: center;
padding: 0px;
height: 110px;
display: table-cell;
vertical-align: middle;
}

and add one more class
.centerpage img {
width:100%;
}

答案 1 :(得分:1)

你可以使用绝对和负边距的旧方法: 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;
}