Home  >  Article  >  Web Front-end  >  CSS various centering methods

CSS various centering methods

高洛峰
高洛峰Original
2016-12-12 14:15:511096browse

css horizontally centered text-align:center and margin:0 auto

These two methods are used for horizontal centering. The former is set for the parent element and the latter is for the child element. The first condition for them to work is that the child elements must not be affected by float, otherwise everything will be in vain. margin:0 auto

can also be written as margin:0 auto 0 auto. Children who don't understand can look for information about CSS abbreviations on their own.

Vertically centered line-height

What? ! Margin doesn't work in vertical centering? Obviously this is the case, we only have the usage of margin:0 auto but not auto 0. As for line-height, it also acts on the parent element. When its value is equal to the height value of the parent element

, the internal text will automatically be vertically centered. It seems that this is just text, which is a pity.

The universal position method

This method can be said to be truly omnipotent. When you are troubled by an element that cannot be centered, you can use it decisively with almost no side effects. It is definitely one of the must-have methods for front-end engineers to travel at home.

The specific method is very simple. First, write positon:relative on the parent element. This is done so that when the child element is marked with position:absolute, it will not be positioned in outer space. Next, write the height and width of the child element. This seems to be necessary

. If some browsers do not have these two values ​​​​when parsing, unexpected misalignment will occur. Then comes the core of the entire method. Add top: 50%; left: 50% and margin-top: a negative number that is half the height value;

margin-left: a negative number that is half the weight value. After sorting it out, you may write css like this for your child elements (of course, the parent element must also write width and height first)

{width:100px;height:80px;position:absolute;top:50% ;left:50%;margin-left:50px;margin-top:40px}

Next, refresh the page. Your child elements are already centered.

The advantage of using this method is that no matter what form of content you have, it can be centered immediately. The disadvantage is that the element must have a certain width and height value, otherwise you may need to perform some small calculations through javascript.


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