CSS display: table-cell: vertical centering of multi-line text

Reference: https://blog.csdn.net/lishuai_it_trip/article/details/88411550?utm_medium=distribute.pc_relevant_t0.none-task-blog-searchFromBaidu-1.control&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog- searchFromBaidu-1.control

Problem: There is a problem with vertical centering of multi-line text

Infeasible method: The general idea is that the height is equal to the line height, but this is only suitable for single-line text, [the second line is not OK]

Infeasible method: flex layout can only set the vertical center of the element, and does not affect the text, so it is wrong. [No effect on text]

Possible methods: display:table and display:table-cell

给父元素<div>设置display:table,
子元素<p>设置display:table-cell,
再加上一个vertical-align:middle(默认情况下,图片,按钮,文字和单元格都可以用vertical-align属性),
于是单行多行的文本垂直居中问题就解决了,不论内容有多少,不论行高是多少,总之都会整体垂直居中
<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div{
            display: table;
            border: 2px solid red;
            width: 500px;
            height: 200px;
        }
        p{
            display: table-cell;
            vertical-align: middle;

        }
    </style>
</head>
<body>
<div>
    <p>
        hello world <br/>
        hello world <br/>
        hello world <br/>
        hello world
    </p>
</div>
</body>
</html>

In fact, this is equivalent to simulating the layout properties of the table, display:table is equivalent to <table>, and display:table-cell is equivalent to <th><td>

Let's take a look at <table>, <th>, <td>, the default properties in the browser:

The parent element of th, td is <tr>, and <tr> is also inherited from the parent element, and the upper part is tbody (the table layout browser will automatically generate this tag),

And the default vertical-align of tbody is middle (this I got certification in IE and Firefox),

So when we add display:table-cell to other labels, there is no such attribute.

So in order to center the text vertically, we need to manually add vertical-align:middle.

 

 

Guess you like

Origin blog.csdn.net/fujian9544/article/details/112218782