1. Single-line text
Vertical centering with high row height and parent element height equality
2. Multiple lines of text
Mode 1:Set the parent element display:table, set the element display:table-cell;vertical-align:middle inside, and the element can be centered vertically, but this way compatibility is not very good the version of the browser is incompatible.
Mode 2:Sets the parent element position:relative Absolute positioning, sets its child elements position:absolute relative to bits, sets top:50%;left:50%, navigates the upper-left corner of the element to the middle of its parent element, and then sets the element width and the height of the normal
Negative margins Move contentTo center the element vertically.
. Container { position: relative;} . Container. Content { position: absolute; top: 50%; Left: 50%; width: 200px; height: 120px; margin-left: -100px; margin-top: -60px;}
Mode 3:
First, combine absolute positioning and position the upper-left corner of the element relative to the middle of the element, then use the CSS3
translate the element is moved (the translate is followed by a percentage that is calculated from the width of the element itself)
. Container { position: relative;} . Container. Content { position: absolute; top: 50%; Left: 50%; Transform: translate ( -50%, -50%);}
Mode 4:
Solution based on viewport units: In a popup dialog box or similar scenario, we want an element to be centered in the viewport. You can use fixed positioning at this time, plus a similar approach to the "absolute location-based solution" mentioned above. In addition, you have another option, which is to use
vhAnd
vwThese two units,
100vwis equal to the width of the viewport, which means
1vwis equal to 1/100 viewport width,
vhIn the same vein,
1vhequals the height of the 1/100 viewport. You can therefore write the following code to center a dialog box in the viewport:
. Dialog { position: fixed; margin-top: 50VH; margin-left: 50vw; Transform: translate ( -50%, -50%);}
Mode 5:
. Container { display: flex;} . Container. Content { margin: auto;}
Mode 6:
. container{
Display:flex;
Justify-content:center;
Align-items:center;
}
CSS Vertical Centering