Horizontal centering: solution for inline elements
Centered elements: text, links, and other inline elements (inline or inline-* type elements, such as inline -block, inline-table, inline-flex)HTML
< div >Text element div >
< nav >
< a href ="" >Link element 01 a >
< a href ="" >Link element 02 a >
< a href ="" >Link element 03 a >
nav >
CSS
nav, div{
text-align: center;
}
Horizontally centered: block element solution
Centered element: block element, such as div, p, section and other elements, that is, the display attribute is Block element
Solution: Add margin-left, margin-right attribute value is auto, such as: margin:0 auto;
Note: Block elements that need to be centered must have a fixed width, otherwise it cannot It is centered because it takes up 100% of the width.
HTML
< div class ="center" >Horizontally centered block element div >
< p class ="center" > ;Horizontally centered block element p >
CSS
div, p{
width: 200px; /* Need to set the width value of the element*/
height: 150px;
color: #fff;
background: #222;
}
.center {
margin: 10px auto;
}
Horizontal centering: Solution for multiple block elements
Centered element: "Multiple block elements" are arranged horizontally and centered in the center
Solution: Set these The display attribute of a block element is inline-block, and the text-align attribute of the parent element is set to center.
Note: If you want to achieve vertical centering of these block elements, use the margin:0 auto attribute in the previous section.
HTML
< div class ="center" >Horizontally centered block element div >
< div class ="center" > ;Horizontally centered block element div >
CSS
body {
text-align: center;
}
/* Page beautification elements*/
div {
width: 100px;
padding: 10px;
height: 50px;
background-color: #222;
color: #fff ;
}
.center {
display: inline-block;
}
Horizontal centering: multiple block elements Solution (implemented using flex layout)
Centered element: Multiple block elements are arranged horizontally and centered (implemented using flex layout)
Solution: Display of the parent element of multiple block elements Just set the property to flex and justify-content:center.
HTML
< div class ="center" >Horizontally centered block element div >
< div class ="center" >Horizontally centered block element Block element
CSS
body {
display: flex;
justify-content: center;
}
/* Page beautification elements*/
div{
width : 100px;
height: 50px;
color: #fff;
background: #222;
margin: 10px;
padding: 10px;
}