Centering is our common problem in CSS, generally have horizontal center, vertical center, vertical horizontal center of the 3 cases, then today first to learn the horizontal center of the method to make a summary notes.
- CSS horizontally centered
- Text-align:center
To see more clearly, let's take an example, we put Div2 into Div1, and now if we want the text to be centered horizontally in div2, then the parent element Div2 or (DIV1) is set to Text-align:center. Because Text-align is inherited, and text-align it is only valid for inline elements.
So then, what if we want Div2 to be centered relative to the div1 level? Since text-align is only valid for inline elements, we'll set Div2 to Display:inline-block; let's look at the effect:
We see the div2 and inside the text are horizontally centered, but we found that the text horizontal center is very ugly, we just want to let div2 horizontal center, which is the shortcomings of this method, child elements of text-align inherit the parent element of the center, text is also centered display, So we need to set the text-align:left in the child element;
This is normal.
2. margin:0 Auto;
margin:0 Auto; Set on its own element to allow block-level elements to be centered horizontally. In the example above we can see that DIV1 is not horizontally centered relative to the page, it is a block-level element, so we just set the div1,div2 to margin:0 auto;
3. Using absolute positioning elements to achieve
(1) The sub-parent is centered horizontally: because the absolute positioning element is scalable, if we set the width of the absolute anchor element to auto, while left and right are set to 0, then the element fills its relative parent element horizontally. At this point if we set the width to a fixed value, margin is auto, as long as left and right values equal (or both 0), and no more than its relative elements minus the absolute positioning element width of half, you can achieve horizontal center.
(2) Using margin negative: The div is set to absolute positioning, the parent element is relative positioning, and then the div's left and top property values are set to 50%, but this time will only make Div's upper right corner center, The Margin-left and Margin-top property values are then set to a negative number, and the value is half the width and height of the div, so that the center of the div is centered, but if it does not have a parent element, or the parent element is not in absolute or relative orientation, Then the window is positioned as the reference object, i.e. the entire div is centered relative to the window.
The effect looks at the following two pictures, figure one in Div1 set relative positioning, div2 for absolute positioning, so div2 in Div1 horizontal center.
In Figure two, the DIV1 is set without positioning and the DIV2 is absolutely positioned, so the div2 is centered relative to the window.
How to center horizontally in CSS