css - 当 div 被限制为偏离中心的有限宽度 div 时,它在页面上水平居中

标签 css

我正在使用一组 HTML 模板,这使得要完全按照我想要的方式自定义有点棘手。所以我坚持使用一种缺乏灵 active 的结构。

我有一个占页面宽度 50% 的 div,但我想在页面中间居中放置一个包含的 div。由于页面其他部分的其他限制,我真的无法更改设置为position: relative 的parent div。

这是我想要的效果: 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;
}

最佳答案

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

相关文章:

php - 如何在 html 或 css 或 javascript 中呈现倾斜图像..?

javascript - 如何在 slick.js 中放大自定义幻灯片

javascript - 使用 jQuery 检测 CSS 文本溢出省略号

html - 将鼠标悬停在链接底部之前,链接不可点击

html - 如何在两个 float 元素之间完美居中 float 元素?

jQuery Sliding Content DIV - 从右边而不是从顶部滑动

html - 如何在超大屏幕中将搜索栏居中?

mobile - 具有三次贝塞尔过渡的星巴克移动导航

html - 将鼠标悬停在导航栏链接上时如何删除此背景?

html - 如何使用 CSS 向此图像 slider 添加单选按钮