Home >Common Problem >How to center css
Css centering method: 1. For horizontal centering, you can use "text-align" for block-level elements, "margin" for block-level elements, and "position" and "transform" for block-level elements; 2. For vertical centering, you can use "line-height" for inline elements, "flexbox" for block-level elements, and "position" and "transform" for block-level elements.
In web design, centering is a very common requirement, especially in layout. CSS provides different methods to achieve centering. Let’s take a look at some of the most common methods.
1. Horizontal centering
1. Use text-align (for block-level elements)
The text-align attribute can horizontally center the internal text of block-level elements. For example, p, h1, h2 and other tags, the sample code is as follows:
div {
text-align: center;
}
2. Use margin (for blocks Level elements)
The margin attribute can horizontally center block-level elements. Just set the left and right margins to auto. The sample code is as follows:
div {
margin: 0 auto;
}
3. Use position and transform (for block-level elements)
The position attribute and transform attribute can achieve horizontal centering of block-level elements. You need to set the position attribute to absolute or fixed, and then use the transform attribute to translate the element 50% to the left. The sample code is as follows:
div {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
2. Vertical centering
1. Use line-height (for inline elements)
The line-height attribute can be used to vertically center inline elements, and set the value of line-height to the container The height of (For block-level elements)
Flexbox is a layout method introduced in CSS3, which can easily achieve vertical centering of elements. You need to set display: flex on the container, and then use align-items: center to vertically center the element. Centered. The sample code is as follows:
.container {
display: flex;
align-items: center;
}
3. Use position and transform (for block-level elements)
The position attribute and transform attribute can also achieve vertical centering of the element. You need to set the position attribute to absolute or fixed, and then use the transform attribute to translate the element upward. 50%. The sample code is as follows:
div {
position: absolute;
top: 50%;
}
Summary:
The above are several ways to achieve centering in CSS. They each have their own advantages and disadvantages. You can choose the appropriate method to achieve your goals in different situations. At the same time, modern browsers are getting better and better in supporting CSS3, and using CSS3’s flexbox layout is also a very convenient choice.
The above is the detailed content of How to center css. For more information, please follow other related articles on the PHP Chinese website!