Today, my blog application was approved. Let me tell you about the various methods I have seen to achieve vertical centering using pure CSS. Why make this the first article? Because this is the most useful knowledge I learned when I first started working with front-end, I hope everyone can benefit from it too!
Implementing horizontal centering in CSS is very simple. Inline elements set thetext-align:center of their parent elements, and block-level elements apply magrin:auto to themselves. However, achieving vertical centering is a bit troublesome. First of all, it is an extremely common requirement. It seems simple, but in practice, it is often difficult to achieve, especially when the design size is not fixed. The following are some methods I found:
Method 1: Line-heightline-height
(1) Single line text centered
HTML code
垂直居中
CSS code
.box1{ height: 200px; } .box2{ line-height: 200px; }
(2)PictureVertically centered
HTML code
CSS code
.box1{ line-height:200px; } .box1 img{ vertical-align: middle; }
Method two: table-cell
CSS code
.box1{ display: table-cell; vertical-align: middle; text-align: center; }
Method three:display:flex
(1) CSS code
.box1{ display: flex; } .box2{ margin:auto; }
(2) CSS code
.box1{ display: flex; justify-content:center; align-items:center; }
Method 4:Absolute positioningAnd negative margin
(1) CSS code
.box1{ position: relative; } .box2{ position: absolute; top: 50%; left: 50%; margin-top: -10px;/*减去子元素高度一半*/ margin-left:-32px;/*减去子元素宽度一半*/ }
(2)CSS code
.box2{ position: absolute; top:calc(50% - 10px);/*减去子元素高度一半*/ left:calc(50% - 32px);/*减去子元素宽度一半*/ }
Method five:Absolute positioning and 0
CSS code
.box2{ width: 50%; height: 50%; background: #555; overflow: auto; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; }
Method six:translate
(1) CSS code
.box2{ position: absolute; top:50%; left:50%; transform:translate(-50%,-50%); }
(2) HTML code
CSS code
.box1{ width: 200px; height: 200px; background: #666; margin: 50vh auto 0; transform: translateY(-50%); }
Method seven:display:-webkit-box
CSS code
.box2{ display: -webkit-box; -webkit-box-pack:center; -webkit-box-align:center; -webkit-box-orient: vertical; text-align: center7 }
The above is the detailed content of Share 7 ways to achieve vertical centering using CSS. For more information, please follow other related articles on the PHP Chinese website!