垂直居中方法。
元素高度不定
position: absolute + transform
水平垂直居中:
1 | // .box元素 |
Flex/Grid + align-items
水平垂直居中:
1 | body { |
Flex/Grid + margin: auto
水平垂直居中:
1 | body { |
See the Pen flex/grid + margin: auto水平垂直居中 by ly023 (@ly023) on CodePen.
vertical-align + 伪元素
vertical-align
用来指定当前inline
元素与其它inline
元素的对齐方式。若只有一个inline
元素,元素无法对齐。可以为父元素添加伪元素,让它的高度与父元素相同。
1 | body::after, |
display: table-cell
使用display:table-cell
,结合vertical-align:middle
以及text-align: center
实现水平垂直居中:
1 | display: table-cell; |
元素高度固定
position: absolute + margin: auto
仅当需要垂直居中的元素具有固定高度时,此方法才有效。
1 | .box { |
解释:Absolute Horizontal And Vertical Centering In CSS
- In the normal content flow, margin: auto; equals ‘0’ for the top and bottom. W3.org: If ‘margin-top’, or ‘margin-bottom’ are ‘auto’, their used value is 0.
- position: absolute; breaks the block out of the typical content flow, rendering the rest of the content as if that block weren’t there. Developer.mozilla.org: …an element that is positioned absolutely is taken out of the flow and thus takes up no space
- Setting top: 0; left: 0; bottom: 0; right: 0; gives the browser a new bounding box for the block. At this point the block will fill all available space in its offset parent, which is the body or position: relative; container. Developer.mozilla.org: For absolutely positioned elements, the top, right, bottom, and left properties specify offsets from the edge of the element’s containing block (what the element is positioned relative to).
- Giving the block a width or a height prevents the block from taking up all available space and forces the browser to calculate margin: auto based on the new bounding box. Developer.mozilla.org: The margin of the [absolutely positioned] element is then positioned inside these offsets.
- Since the block is absolutely positioned and therefore out of the normal flow, the browser gives equal values to margin-top and margin-bottom centering the element in the bounds set earlier. W3.org: If none of the three [top, bottom, height] are ‘auto’: If both ‘margin-top’ and ‘margin-bottom’ are ‘auto’, solve the equation under the extra constraint that the two margins get equal values. AKA: center the block vertically
在正常流中,
margin: auto
相当于top和bottom设置为0;w3.org normal-block If ‘margin-top’, or ‘margin-bottom’ are ‘auto’, their used value is 0
position: absolute
会使这个块脱离正常的文档流设置绝对定位元素的四个定位属性为具体数值时(如
top: 0; left: 0; bottom: 0; right: 0;
),为该元素提供了一个新的边界盒(bounding box)。 此时,该元素将填充其偏移父元素(指position: relative
定位的父元素或body
)的所有可用空间;给这个块指定
width
或者height
会阻止它占用所有可用空间,转而由浏览器根据新的边界盒自动计算margin由于这个块脱离了正常的文档流,同时有一个新的边界盒,因此浏览器可以很容易地为它提供相等的
margin-top
与margin-bottom
值,从而使它垂直居中。