Center Method, vertical center Method
Today, when I wrote a webpage, I found that center is a headache. So I summarized what I know on the Internet and my usage to solve the center problem:
1. text-align: center
It must be set on the parent element. It can only be a text or line element and cannot beFloating Element
.div1{ text-align: center; }<div class="div1"> <span>text-alignf</span></div>
2. margin: 0 auto
It must be set on the child element. It can only be a block-level element and cannot beFloating Element
.div2 div{ margin: 0 auto; }<div class="div2"> <div> <p>margin</p> </div></div>
3. line-height
It must be set on the parent element. It can only be a text or line element.
.div3{ line-height: 200px; }<div class="div3"> <span>line-height</span></div>
4. position
First, write the positon positioning for the parent and child elements respectively, and then set the width and height for the parent and child elements,
Then write the top: 50%; left: 50%; and the negative number of the height value of the half of the margin-top;
Margin-left: negative number of weight Values in half. (The principle is to first place the child element on the 50% (WXH) of the parent element, and then subtract the height (WXH) of the child element.
Half)
.div4{ position:relative; } .div4 div{ /*float: left;*/ width:100px; height:80px; position:absolute; top:50%;left:50%; margin-left:-50px; margin-top:-40px }<div class="div4"> <div> <p> position </p> </div></div>
5. inline-block
Set the text-align: center for the parent element, and set the display: inline-block for the element to be centered (set the parent element to a row element and block-level element to itself)
.div5{ text-align: center; } .div5 div{ display: inline-block; }<div class="div5"> <div> <p> inline-block </p> </div></div>