How to implement css top and bottom centering: 1. Set the row height of a single row of inline elements equal to the box height; 2. Use multiple rows of inline elements to set "display:table-cell; and vertical- align: middle;" is enough.
Top and bottom centering in css is vertical centering. There are three vertical centering methods in css based on elements, namely single-line inline elements and multi-line Vertical centering of inline elements and block elements will be introduced in detail below.
Single-line inline elements
You only need to set the "row height equal to the height of the box" for the single-line inline element;
<style> #father { width: 500px; height: 300px; background-color: skyblue; } #son { background-color: green; height: 300px; } </style> <div id="father"> <span id="son">我是单行的行内元素</span> </div>
Effect:
Multi-line inline elements
Use to the parent element Just set display:table-cell; and vertical-align: middle;;
<style> #father { width: 500px; height: 300px; background-color: skyblue; display: table-cell; vertical-align:middle; } #son { background-color: green; } </style> <div id="father">
I am an inline element with multiple lines I am an inline element with multiple lines I am I am an inline element with multiple lines I am an inline element with multiple lines I am an inline element with multiple lines I am an inline element with multiple lines I am an inline element with multiple lines
Effect:
# Block-level elements
Option 1: Use positioning
First set the parent element to relative positioning, then set the child element to absolute positioning, set the top of the child element: 50%, that is, make the upper left corner of the child element vertical Centered; Fixed height: Set the margin-top of the absolute child element: -half px of the element height; or set transform: translateY(-50%);<style> #father { width: 500px; height: 300px; background-color: skyblue; position: relative; } #son { height: 100px; background-color: green; position: absolute; top: 50%; margin-top: -50px; } </style> <div id="father"> <div id="son">我是块级元素</div> </div>
<style> #father { width: 500px; height: 300px; background-color: skyblue; position: relative; } #son { width: 100px; background-color: green; position: absolute; left: 50%; transform: translateY(-50%); } </style> <div id="father"> <div id="son">我是块级元素</div> </div>
Option 2: Use flexbox layout to implement (the height is variable All are OK)
<style> #father { width: 500px; height: 300px; background-color: skyblue; display: flex; align-items: center; } #son { width: 100px; height: 100px; background-color: green; } </style> <div id="father"> <div id="son">我是块级元素</div> </div>
The above is the detailed content of How to center the top and bottom in css?. For more information, please follow other related articles on the PHP Chinese website!