垂直居中在未知高度DIV内的DIV

时间:2017-04-02 07:23:44

标签: html css

我目前有这个HTML:

<div id:root>
  <div id:contents>
    <h3>I am the one that need to be vertical centered.</h3>
    <p>Lorem300..............</p>
  </div>
  <img scr:"somewhere.jpg"></img>
</div>

目前的SASS:

img
  width: 100%
  height: inherit

我想解决的问题是我想要&#39; root&#39; DIV与img具有完全相同的大小。在这种情况下,img宽度设置为100%,这意味着它始终占据视口宽度的100%。有没有办法让我可以垂直居中“内容”。 DIV到&#39; root&#39; DIV?非常感谢你。我花了一整天仍然没有找到。即使我使用:

#contents
  top: 50%
  transform: translateY(-50%)

&#39;内容&#39; div取身体的高度,而不是根部的高度。 DIV。 :(

有没有办法解决这个问题?谢谢!

2 个答案:

答案 0 :(得分:0)

<div class="portaal portaal_links"></div>
<div class="portaal portaal_rechts"></div>
.center_block{
	  position: absolute;
    top: 50%;
    left: 50%;
    -ms-transform: translateX(-50%) translateY(-50%);
    -webkit-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
}

答案 1 :(得分:0)

您可以使用css flexbox来帮助您集中#contents

只需使用这些属性设置#root

#root {
  position: relative; /* needed to position img absolutely with div */
  display: flex; /* make this element flexbox */
  justify-content: center; /* horizontally center children */
  align-items: center; /* vertically center children */
}

然后提供#contentsimg这些属性

#contents {
  position: relative; /* needed to set z-index */
  z-index: 2; /* make #contents above img */
}

img {
  position: absolute;
  top: 0px;
  left: 0px;
  height: 100%;
}

例如,请参阅this fiddle。您可以从上面的链接中了解有关css flexbox的更多信息。

希望这有帮助,

相关问题