Home > Article > Web Front-end > How to achieve horizontal centering of variable width in css
Method: 1. Use flex layout and set both ustify-content and align-items attributes to center to achieve centering; 2. Use transform and position attributes to achieve centering; 3. Use table-cell and use Table cell centering effect.
The operating environment of this tutorial: Windows 7 system, css3 version. This method is suitable for all brands of computers.
Recommended: "css video tutorial"
css achieves horizontal centering of variable width
Method 1: Use flex
Everyone’s first reaction may be flex. Because its writing method is simple and intuitive enough, and there is no problem with compatibility. It is the first choice for centering on mobile phones.
<div class="wrapper flex-center"> <p>horizontal and vertical</p> </div>
.wrapper { width: 300px; height: 300px; border: 1px solid #ccc; } .flex-center { display: flex; justify-content: center; align-items: center; }
Using two key attributes: justify-content and align-items, both are set to center to achieve centering.
It should be noted that the flex-center here must be hung on the parent element so that the only child element can be centered.
Method 2: Use transform position
This combination is often used to center the image.
<div class="wrapper"> <img src="test.png"> </div>
.wrapper { width: 300px; height: 300px; border: 1px solid #ccc; position: relative; } .wrapper > img { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); }
Of course, you can also move the relative positioning of the parent element wrapper into the child element img and replace the absolute positioning. The effect is the same.
Method 3: table-cell
Use the table's cell centering effect to display. Like flex, it needs to be written on the parent element.
<div class="wrapper"> <p>horizontal and vertical</p> </div>
.wrapper { width: 300px; height: 300px; border: 1px solid #ccc; display: table-cell; text-align: center; vertical-align: middle; }
Method 4: grid
Like a table, a grid layout allows us to align elements by rows or columns. However, in terms of layout, grids are more possible or simpler than tables.
<div class="wrapper"> <p>horizontal and vertical</p> </div>
.wrapper { width: 300px; height: 300px; border: 1px solid #ccc; display: grid; } .wrapper > p { align-self: center; justify-self: center; }
But it is not as good as flex in terms of compatibility, especially the IE browser, which only supports IE10 and above.
For more programming-related knowledge, please visit: Introduction to Programming! !
The above is the detailed content of How to achieve horizontal centering of variable width in css. For more information, please follow other related articles on the PHP Chinese website!