Home >Web Front-end >Front-end Q&A >How to center css
In front-end development, centered layout is a common requirement, especially in mobile development. In order to align the style and visual beauty, we need to center the elements. Here are some common CSS centering methods.
1. Horizontally centered layout
This is the most commonly used horizontal centering method. Just add the left and right margins of the element. Just set it to auto. This method works for block elements, but does not work when your element is absolutely positioned or floated.
.box { width: 200px; margin: 0 auto; }
When the element you need to center horizontally is an inline element, you can use the text-align: center attribute to set its parent container Just center the text.
.parent { text-align: center; } .child { display: inline-block; }
Flex layout is a powerful CSS layout method that can easily achieve many centering effects. Using flexbox, we can place child elements in the center of the parent container.
.parent { display: flex; justify-content: center; } .child { width: 50px; }
2. Vertical centering layout
This is the simplest vertical centering method, just change the line-height of the element Just set it equal to its height.
.box { height: 80px; line-height: 80px; }
Using the display: table and table-cell attributes, you can easily achieve the vertical centering effect of elements.
.parent { display: table; } .child { display: table-cell; vertical-align: middle; }
Like horizontal centering, vertical centering of elements can also be achieved using Flexbox.
.parent { display: flex; align-items: center; } .child { height: 50px; }
3. Horizontal and vertical centering layout
Using absolute positioning and negative margin can easily achieve horizontal and vertical centering of elements. .
.parent { position: relative; } .child { position: absolute; top: 50%; left: 50%; margin-top: -25px; /* height/2 */ margin-left: -25px; /* width/2 */ height: 50px; width: 50px; }
Using Transform can also achieve horizontal and vertical centering of elements. Just set the translateX and translateY attributes of the element to -50%.
.parent { position: relative; } .child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); height: 50px; width: 50px; }
Flexbox is also the best choice for horizontal and vertical centering of elements. Set the element's parent container to display: flex, and then use the justify-content and align-items properties to achieve centered layout.
.parent { display: flex; justify-content: center; align-items: center; } .child { height: 50px; width: 50px; }
The above are the common CSS centering methods. In actual development, the most suitable centering method should be selected based on the type, structure, needs and other factors of the element.
The above is the detailed content of How to center css. For more information, please follow other related articles on the PHP Chinese website!