In general, it is relatively simple to horizontally center a fixed-width block element, and we only need to set the width of the block element and set margin:0 Auto. However, for block elements that cannot be set to a fixed width, this trick does not work.
Let me introduce the three commonly used methods to set the horizontal center of an indefinite wide block element.
First: horizontal centering with float+relative
CSS code:
. Wrap { float: left; position: relative; Left:50%; border: 1px solid red; } . Content{ position: relative; left: -50%; border:1px solid Blue; }
HTML code
<class= "wrap"> <class= " Content "> What needs to be centered </div> </ div>
Second: Horizontal centering using table
CSS Code
. Wrap{ margin:0 auto; Border: 1px solid red; } . Content{ border: 1px solid blue; }
HTML code
<Tableclass= "Wrap"> <TR> <TD> <Divclass= "Content">Content that needs to be centered</Div> </TD> </TR> </Table>
Third: Use Display:inline to achieve horizontal centering (Inline-block effect is the same)
CSS Code
. Wrap{ text-align: center; Border: 1px solid red; } . Content{ display: inline;/*inline-block can also */ border : 1px solid blue; }
HTML code
<class= "wrap"> <class= " Content "> What needs to be centered </div> </Div >
The method of horizontal centering of three kinds of indefinite wide block elements