Summarize the methods of CSS center and summarize the methods of css center.
Using CSS to Center page elements may be the most common obstacle in our page development. Next, let's summarize several common center methods.
1. First, let's talk about horizontal center:
- Combination of text-align and inline-block
Like this:
See the Pen mVpVEr by xal821792703 (@ honoka) on CodePen.
In HTML, a parent element is set outside the element to be centered, and the text-align attribute of the parent element is set to center in CSS, set the display attribute of the child element to inline-block to horizontally center the child element.
- Implemented through margin
See the Pen rxpxmR by xal821792703 (@ honoka) on CodePen.
With the help of margin, you don't need to set the parent element. Instead, you can use margin: 0 auto. That's right. That's so simple and quick. I'm afraid it's the most common method for center.
2. As a result, the boss said that the horizontal center would not work, but the vertical center would be required:
- Let's use margin to realize the vertical center of the absolute positioning element.
See the Pen NxXxBz by xal821792703 (@ honoka) on CodePen.
Pay attention to several key points in the Code:
-
- Absolute positioning of sub-element div
- Parent element needs to be located
- The values of the top, bottom, left, and right sub-elements are 0.
- Sub-element margin: auto;
- New kill flex from CSS3
See the Pen xZpZMw by xal821792703 (@ honoka) on CodePen.
The key to horizontal vertical center using the flex container layout is:
-
- Set the display attribute of the parent element to flex.
- The vertical layout attribute is align-items. If it is set to center, the vertical layout is centered.
- The attribute of the horizontal layout is justify-content. If it is set to center, it is horizontally centered.
- The sub-element is elastically centered, and adding sub-element does not affect
For compatibility issues, see:
In fact, there are still many ways to center by using CSS. I have not written it in my blog post. How to choose the Center technical solution depends on the browser support and coverage in the current business scenario.