Article Introduction: centering has always been a form of placement that designers prefer to use, whether the picture or text will be asked to be placed in the middle, horizontally or vertically. CSS provides a lot of convenient ways to get content centered, and here's a list of the most used centering techniques. |
Centering has always been a form of placement that designers prefer to use, whether the picture or text will be asked to be placed in the middle, horizontally or vertically. CSS provides a lot of convenient ways to get content centered, and here's a list of the most used centering techniques.
Horizontally centered Text-align:center and margin:0 auto
Both of these methods are used to center horizontally, which is set for the parent element and the latter for the child element. The first condition that they work is that the child elements must not be affected by float, otherwise all is useless work. Margin:0 Auto can also be written as margin:0 Auto 0 auto. Unable to understand the children's shoes can find their own content about CSS abbreviations.
Line-height in Vertical Center
What the?! Does the margin not work in the vertical center? Obviously this is true, we only have margin:0 auto usage without auto 0. As for Line-height, he also acts on the parent element, and when his value equals the height value of the parent element, the inner text is automatically centered vertically. Here seems to be only words, sorry.
The Almighty position Dafa
This method can be said to be truly omnipotent. When you are unable to center for an element of the time, can be determined to use him, and almost no sequelae, is absolutely the front-end engineers home travel must be one of the means.
The concrete practice is very simple, first writes the positon:relative to the Father element, this does is in order to give the child element to play the Position:absolute time not to be positioned in outer space to go. Next, write the child element of height and width, this seems to be necessary, some browsers in the parsing time without these 2 values will appear unexpected dislocation. Then there is the core of the whole method, and then the top:50%;left:50% and margin-top: The negative number of half the height value, margin-left: Half of the weight value. After tidying up, you may be able to write CSS to your child elements (and, of course, the parent must write the width and height first).
{width:100px;height:80px;position:absolute;top:50%;left:50%;margin-left:50px;margin-top:40px}
Then refresh the page, and your child elements are already centered.
The advantage of using this method is that no matter what form your content can be centered right away, the disadvantage is that you have to have a certain width to the element, otherwise you might need to do some small calculations with JavaScript.