I was asked during the interview: How to vertically center a text with variable width and height?
Now let’s summarize:
Write the structure in the body
Method 1:
#main{
position: relative; //Use relative positioning in the parent element
width: 200px;
height: 200px;
overflow: hidden;
background-color: #ff0;
padding: 10px;
}
#login{
position: absolute; /*Use absolute positioning in child elements*/
top :50%; /*Distance relative to 50% of the height of the parent element*/
left:50%;
background-color: #eee ;
-webkit-transform:translate(-50%,-50%); /*CSS3 style, :translate(-50%,-50%) is relative to -50% of its distance from the x-axis and y-axis */
}
Method 2:
#main{
width: 200px;
height: 200px;
background-color: #eee;
display: table; /*Let the label elements be presented in the form of table*/
}
#login{
display: table-cell; /* Neither ie7 nor ie6 can recognize display: table-cell;*/
vertical-align: middle;
}
The above is the detailed content of Three ways to vertically center text with variable width and height in divs. For more information, please follow other related articles on the PHP Chinese website!