Home > Article > Web Front-end > 6 CSS Horizontal and Vertical Centering Solutions
This article mainly introduces to you the relevant information about CSS horizontal and vertical centering solutions (6 types). The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
Preparation
Create element
<p class="parent"> <p class="child">child</p> </p>
Vertical and horizontal centering solution one: absolute+margin negative value when the width is known
.parent { width:400px; height:400px; background: red; position: relative; } .child { position: absolute; left:50%; top:50%; background: yellow; width:50px; height:50px; margin-left:-25px; margin-top:-25px; }
Vertical and horizontal Centering option two: Absolute+transform
.parent { width:400px; height:400px; background: red; position: relative; } .child { position: absolute; left:50%; top:50%; transform: translate(-50%,-50%); }
Vertical centering option three: position+margin:auto
.parent { position:relative; width:200px; height:200px; background: red; } .child { width:80px; height:40px; background: yellow; position: absolute; left:0; top:0; right:0 ; bottom:0; margin:auto; }
Vertical centering option four: + Multi-line text Vertical centering: table-cell+vertical-align:middle;
.parent { height: 300px; width:400px; border: 1px solid red; display: table-cell; vertical-align: middle; text-align: center; } .child { display: inline-block; width:50px; height:50px; background: blue; } /* 或者 */ .parent { width: 400px; height: 300px; display: table-cell; vertical-align: middle; border: 1px solid red; text-align: center; } .child { display: inline-block; vertical-align: middle; background: blue; }
Vertical centering solution five: display: flex
.parent { width:400px; height:200px; background:red; display: flex; justify-content:center; align-items:center; } .child { height:100px; width:100px; background:green; }
Vertical centering solution six: Pseudo elements
.parent { width:200px; height:200px; background:red; text-align: center; } .child { height:100px; width:100px; background:yellow; display: inline-block; vertical-align: middle; } .parent:before { content:""; height:100%; vertical-align: middle; display: inline-block; }
Related recommendations:
4 ways to achieve horizontal and vertical centering in css
How to set the horizontal and vertical centering of HTML elements
How to achieve horizontal, vertical centering and both-end alignment code sharing in css
The above is the detailed content of 6 CSS Horizontal and Vertical Centering Solutions. For more information, please follow other related articles on the PHP Chinese website!