This article introduces you to the content of CSS common horizontal vertical center of the implementation of how to do? CSS in the three common horizontal vertical center, there is a certain reference value, the need for friends can refer to, I hope to help you.
When you do not know the width and height of the child elements, how to achieve the horizontal vertical center of the child elements, here are summed up several methods:
1, the use of positioning and transform realization
The HTML and CSS code are as follows:
<div class= "Super-div" > <div class= "Sub-div" > Using positioning and Transform <br/> for horizontal vertical centering </div> </div> . super-div { width:400px; height:300px; border:1px solid black; } . sub-div { background-color:green; position:relative; top:50%; left:50%; Transform:translate ( -50%, -50%); /* top Left respectively relative to the height and width of the parent element, translate relative to its own width and height */ }
The core of this implementation is the annotation section, when relative positioning, top and left are relative to the parent element's height and width calculation, and the transform is relative to its own width and height calculation, the effect is as follows:
2, using Table-cell layout to achieve
HTML and CSS code are implemented as follows:
<div class= "Super-div table" > <div class= "Table-cell" > Using Table-cell <br/> for horizontal vertical centering </ div> </div> super-div { width:400px; height:300px; border:1px solid black; } . Table { display:table; } . Table-cell { Display:table-cell; /* Vertical Center */ Vertical-align:middle; /* Horizontal Center */ Text-align:center; Background-color:green; }
The parent element sets the table layout, and the child elements are set to the Table-cell layout. The child elements are then centered vertically horizontally, with the following effect:
3, using the Flex layout to achieve
The HTML and CSS code are as follows:
<div class= "Super-div flex" > <div class= "Flex-center" > Leverage Flex Layout <br/> Achieve horizontal vertical centering </div ></div> . super-div { width:400px; height:300px; border:1px solid black; } . Flex { Display:flex; /*flex layout */ justify-content:center; /* Align the sub-project horizontally */ align-items:center; /* Center The subproject vertically */ } . flex-center { background-color:green; }
The implementation results are as follows: