CSS vertical horizontal center, css vertical center
By summarizing the basic methods of horizontal center and vertical center, the method of combing vertical horizontal center is not so messy.
- Text-align: center + line-height
For example, in div2, text-align + line-height is used to center a single line of text horizontally and vertically.
You can also set div2 to inline-block to implement vertical and horizontal center of the div.
- Text-align: center + vertical-align: middle
To center div2 in div1, you need to set the parent element to text-align: center, because the center effect is only valid for text content and in-row elements, then we set the sub-element div2 to the inline-block element, and set the parent element to the table-cell element, vertical-align: middle,
- Margin: 0 auto + vertical-align: middle
Margin: 0 auto; it can be set on its own element to realize horizontal center of block-level elements, so set the child element to margin: 0 auto; set the parent element to the table-cell element, and vertical-align: middle.
- Absolute positioning achieves vertical and horizontal center
Absolute positioning element vertical and horizontal center: Because absolute positioning elements are scalable, if we set the width of the absolute positioning element to auto, and set left and right to 0, then the element is filled with its parent element horizontally. At this time, if we set the width to a fixed value and the margin to auto, as long as the left and right values are equal (or both are 0 ), the horizontal center can be achieved if the value does not exceed half of the width of the relative element minus the absolute positioning element. The same is true for vertical center, as long as the value of top and bottom is equal or both 0, so that our absolute positioning element achieves vertical and horizontal center.