是否可以垂直居中相对定位的元素?

时间:2016-11-11 19:16:11

标签: css

我正在尝试垂直居中图像。我知道如何用绝对位置来做到这一点,但问题在于它周围的其他元素会陷入其中。

这是我使用绝对位置垂直居中的方式:

.element {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}

我想使用相对位置,但是当我将绝对值更改为相对位置时,它不起作用。有人建议使用相对位置垂直居中吗?我可以做填充/边距顶部,直到它居中,但我希望css生成它居中,以防图像在响应时改变高度。

这是HTML和CSS,非常简单:

<div class="header-main-left">
    <img src="/images/header_logo.png" >
</div>

.header-main-left {
    float: left;
    height: 95px;
    position: relative;
}

.header-main-left img {
    position: absolute; //I want this to be position relative
    top: 50%;
    transform: translateY(-50%);
}

2 个答案:

答案 0 :(得分:2)

position:relative不会从流中取出一个元素,它只允许您相对于未被定位时渲染的位置更改其渲染位置。

position:absolute从文档流中获取一个元素。这会导致元素原点位于最近的祖先元素的左上角,而不是position:static

如果您需要将特定元素设置为position:relative,但需要将其初始位置置于其父级中心,请添加包装元素并将居中移动到该包装器。

.header-main-left {
    float: left;
    height: 95px;
    position: relative;
}

.header-main-left .logo-wrapper {
    position:absolute;
    top:50%;
    height:100%; /* let the relative top and transform on the img work */
}

.header-main-left img {
    position: relative; /* I want this to be position relative */
    top:50%;
    transform: translateY(-50%);
}
<div class="header-main-left">
  <div class="logo-wrapper">
    <img src="/images/header_logo.png" >
  </div>
</div>

答案 1 :(得分:0)

尝试使用    显示:table-cell; 比垂直对齐设置为中心

或使用表格。

或者使用Jquery将元素上的margin-top添加到其高度的一半

相关问题