7 methods for vertical center with pure CSS, 7 methods for vertical center with css
Today, I applied for a blog and told you about the various methods for vertical center of pure css that I have seen. Why is it the first article? This is the most useful knowledge I have learned from the front-end. I hope you can also benefit from it!
It is very easy to implement horizontal center in CSS. The text-align: center of the parent element is set for the row element, and the block-level element applies magrin: auto to itself. However, it is a bit difficult to implement vertical center. First, it is an extremely common requirement, seemingly simple. In practice, it is often difficult to climb the sky, especially when the design size is not fixed. Here are some of the methods I have found:
Method 1: line height line-height
(1) center a single line of text
HTML code
1 <div class = "box1"> 2 <div class = "box2"> vertical center </div> 3 </div>
CSS code
1 .box1{2 height: 200px;3 }4 .box2{5 line-height: 200px;6 }
(2) vertical center
HTML code
1 <div class="box1">2 3 </div>
CSS code
1 .box1{2 line-height:200px;3 }4 .box1 img{5 vertical-align: middle;6 }
Method 2: table-cell
CSS code
1 .box1{2 display: table-cell;3 vertical-align: middle;4 text-align: center;5 }
Method 3:Display: flex
(1) CSS code
1 .box1{2 display: flex;3 }4 .box2{5 margin:auto;6 }
(2) CSS code
1 .box1{2 display: flex;3 justify-content:center;4 align-items:center;5 }
Method 4:Absolute positioning and negative margin
(1) CSS code
1. box1 {2 position: relative; 3} 4. box2 {5 position: absolute; 6 top: 50%; 7 left: 50%; 8 margin-top:-10px;/* minus half of the height of the child element */9 margin-left: -32px;/* Minus the width of the sub-element in half */10}
(2) CSS code
1. box2 {2 position: absolute; 3 top: calc (50%-10px);/* Minus the height of the child element half */4 left: calc (50%-32px ); /* minus half the width of the child element */5}
Method 5:Absolute positioning and 0
CSS code
1 .box2{2 width: 50%;3 height: 50%;4 background: #555;5 overflow: auto;6 margin: auto;7 position: absolute;8 top: 0; left: 0; bottom: 0; right: 0;9 }
Method 6:Translate
(1) CSS code
1 .box2{2 position: absolute;3 top:50%;4 left:50%;5 transform:translate(-50%,-50%);6 }
(2) HTML code
1 <body>2 <div class="box1">3 </div>4 </body>
CSS code
1 .box1{2 width: 200px;3 height: 200px;4 background: #666;5 margin: 50vh auto 0;6 transform: translateY(-50%);7 }
Method 7:Display:-webkit-box
CSS code
1 .box2{2 display: -webkit-box;3 -webkit-box-pack:center;4 -webkit-box-align:center;5 -webkit-box-orient: vertical;6 text-align: center7 }