简体   繁体   English

垂直居中-如何使内嵌元素垂直保持在块级元素的中间

[英]Vertical Centering - How to keep an inline element in the middle of a block-level element vertically

I have a <div> that is containing a sentence. 我有一个<div> ,其中包含一个句子。 The height of <div> is based of % (its height is changeable - depends on size of screen) . <div>的高度基于% (其高度是可变的-取决于屏幕的大小) Now I want to keep that sentence in the center (vertically) of <div> , How can I do that? 现在,我想将该句子保持在<div>的中心(垂直),我该怎么做?

Here is a sample of what I said: 这是我说的一个例子:

 div{ position:absolute; border: 1px solid; width: 250px; height: 60%; text-align: center; } 
 <div>This should be center vertically</div> 

Use flexbox 使用flexbox

 div{ position:absolute; border: 1px solid; width: 250px; height: 60%; text-align: center; display: flex; align-items: center; justify-content: center; } 
 <div>This should be center vertically</div> 

My favorite technique is to add an ::after pseudo-element to the parent element, wrap all the element's children in a single element, and let that element and the ::after pseudo-element play the inline-block, vertical-alignment game: 我最喜欢的技术是在父元素中添加::after伪元素,将所有元素的子元素包装在单个元素中,然后让该元素和::after伪元素玩内联块,垂直对齐游戏:

 div{ position:absolute; border: 1px solid; width: 250px; height: 60%; text-align: center; } div span { display: inline-block; vertical-align: middle; } div::after { content: ''; display: inline-block; height: 100%; vertical-align: middle; } 
 <div><span>This should be centered vertically, and now it is!</span></div> 

The ::after pseudo-element having height: 100% will expand dynamically with the height of the parent, thus the inner element will always be centered vertically. height: 100%::after伪元素将随着父对象的高度动态扩展,因此内部元素将始终垂直居中。

Seen two methods already. 已经看到两种方法。 Here is another method using table and table-cell. 这是使用table和table-cell的另一种方法。 give display: table to parent and table-cell and vertical-align: middle to the child and see the magic. display: table父级table-celltable-cellvertical-align: middle子级vertical-align: middle ,看魔术。

 div{ position:absolute; border: 1px solid; width: 250px; display: table; height: 60%; text-align: center; } div span { display: table-cell; vertical-align: middle; } 
 <div><span>This should be centered vertically</span></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM