About the table-cell attribute in the display attribute

display: table-cell achieves vertical centering

When working on a project, I found that an attribute is particularly easy to use. It can easily realize the horizontal and vertical centering of the in-line elements in the parent element, especially a p tag because the text is too long and wraps. At this time, it needs to be centered horizontally and vertically, and its display attribute can be adjusted. The value is set to the table-cell attribute, the display of the parent element is set to the other table, combined with vertical-aglin:midddle to make it vertically centered, and text-aglin:center to make it horizontally centered so that the effect of horizontal and vertical centering is achieved. The effect can be achieved through the following code:

<div class="box1">        
<p>这是一个网页这是一个网页这是一个网页</p>    
</div>
 .box1{
    
                
 width: 200px;            
 height: 150px;            
 border: 1px solid darkcyan;        
 }   

The effect before adding the code:
Insert picture description here
Modify the code:

 .box1{
    
                
 width: 200px;            
 height: 150px;            
 border: 1px solid darkcyan;            
 display: table;        
 }        
 p{
    
                
 display: table-cell;            
 vertical-align: middle;            
 text-align: center;            
 width: 200px;            
 height: 16px;        
 }

Effect picture: In
Insert picture description here
this way, the horizontal and vertical centering is realized.
Under normal circumstances, we will use the line height, that is, the value of line-height and the height of the parent element to achieve vertical centering, and text-aglin to achieve horizontal centering, but when there is too much content to wrap, this method is not available , This will overflow the text.

Guess you like

Origin blog.csdn.net/qq_44902858/article/details/109698120