For fixed-width non-floating elements we can be horizontally centered in CSS with margin:0 auto, and we have a common technique to solve the problem of horizontal centering for variable-width floating elements. To solve the problem of horizontal centering there are many ways, the following first to share a few three ways, I hope to help everyone.
Method One:
1. HTML part:
<div class= "box" > <p> I am floating </p> <p> I am also centered </p></div>
2. CSS part:
. box{float:left; position:relative; left:50%;} p{float:left; position:relative; right:50%;}
So it seems simple, the parent and child elements are floating at the same time, then the parent element moves relative to the left by 50%, then the child element moves relative to the right 50%, or the child element moves relative to the left-50%. So simple and so magical.
Method Two:
HTML Code
<! DOCTYPE html>
The parent and child elements are left floating at the same time, then the parent element moves relative to the left by 50%, and then the child element moves relative to the left-50%.
Method Three:
HTML code
<! DOCTYPE html>
Here can also set a layer of left:-50%, more reasonable, also can avoid some unnecessary ie BUG. Extrapolate, the way the float element is centered can actually be extended to many situations where floating elements need to be centered.
There are three ways to teach CSS how to center a floating element horizontally
How CSS allows floating elements to be centered horizontally