且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

垂直居中的内容超过窗口高度

更新时间:2022-06-03 09:53:11

当我需要垂直对齐一个元素时,尝试改变高度和宽度,你会注意到它是如何自动计算以居中元素。

This is generally what I tend to use when I need to align an element vertically. Try changing the height and width and you will notice how it automatically calculates to center the element.

div.container{
    width: 300px;
    height: 300px;
    position: relative;
  
    background: salmon;
}

div.container > div.wrapper{
    position: absolute;
  
    top: 50%;
    left: 50%;
  
  
    -webkit-transform: translate(-50%, -50%);
       -moz-transform: translate(-50%, -50%);
            transform: translate(-50%, -50%);
  
    background: red;
}

<div class='container'>
    <div class='wrapper'>
      <label>Some text</label>
      <label>Some more text</label>
    </div>
</div>