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

高洛峰
Release: 2017-03-31 10:57:33
Original
2255 people have browsed it

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!