Home  >  Article  >  Web Front-end  >  Three ways to vertically center text with variable width and height in divs

Three ways to vertically center text with variable width and height in divs

高洛峰
高洛峰Original
2017-03-31 10:57:332213browse

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

main">
< div id="login">
djshdk awjdsd sede sfcdf vdj sh dkaw jds dse desf cdf vd jsh dkawjd sds ede sfcdfv vd jsh dkawjd sds ede sfcdfv.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn