【问题标题】:Vertical Centering a DIV within an unknown height DIV在未知高度 DIV 内垂直居中 DIV
【发布时间】:2017-04-02 17:09:32
【问题描述】:

我目前有这个 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

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

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

'contents' div 采用 body 的高度,而不是 'root' div。 :(

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

【问题讨论】:

  • 是的,带有ghost element
  • 您与#contents { top: 50%; transform: translateY(-50%)' } 是对的。只需添加#contents { display:absolute }#root { position:relative }

标签: html css


【解决方案1】:

.center_block{
	  position: absolute;
    top: 50%;
    left: 50%;
    -ms-transform: translateX(-50%) translateY(-50%);
    -webkit-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
}
<div class="center_block">
  <div>
    <h3>I am the one that need to be vertical centered.</h3>
    <p>Lorem300..............</p>
  </div>
  <img scr="somewhere.jpg" class="img-responsive" />
</div>

【讨论】:

    【解决方案2】:

    您可以使用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 的信息。

    希望这会有所帮助,

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-26
      • 1970-01-01
      • 2016-01-19
      • 1970-01-01
      • 2018-01-20
      • 1970-01-01
      • 2017-07-29
      • 2013-06-24
      相关资源
      最近更新 更多