CSS vertical horizontal center, css vertical center
To sum up, text-align: center is used for horizontal center of elements in the row, margin-left: auto is used for horizontal center of block-level elements, and margin-right: auto is used for horizontal center;
First, we will discuss the situation of a single row.
There is no doubt that this is the simplest case.
The HTML structure is as follows:
1 <div class="demo">2 <span>111111111111111111111111111111111111</span>3 </div>
The height is not fixed (this method is also applicable when multiple texts are written and will not be discussed below)
1 .demo {2 text-align: center; 3 padding-top: 20px;4 padding-bottom: 20px;5 }
Fixed height
1 .demo {2 text-align: center;3 height: 100px;4 line-height: 100px;5 }
Next, we will discuss the situation of multiple rows.
The HTML structure is as follows:
1 <div class="demo">2 <span>111111111111111111111111111111111111<br />22222222222222222222</span>3 </div>
When the height is not fixed, you only need to add the pading value.
Fixed height
Method 1: Set "display: table" for the parent element and "display: table-cell" for the child element. The table feature is used.
1 .demo { 2 height: 100px; 3 display: table; 4 margin-left: auto; 5 margin-right: auto; 6 } 7 .demo span { 8 display: table-cell; 9 vertical-align: middle;10 }
Method 2: Set position: relative for the parent element and position: absolute for the child element. It mainly utilizes the characteristics of the Center of translate relative to the element itself.
1 .demo { 2 position: relative; 3 height: 100px; 4 } 5 6 .demo span { 7 position: absolute; 8 left: 50%; 9 top: 50%;10 -webkit-transform: translate(-50%, -50%);11 -ms-transform: translate(-50%, -50%);12 transform: translate(-50%, -50%);13 }
Method 3: Use flex layout.
.demo { height: 100px; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-pack: center; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center;}
Method 4: vertical center is implemented using the following: after,: before pseudo class, And the inline-block feature.
1 .demo { 2 height: 100px; 3 text-align: center; 4 } 5 6 .demo:after, .demo:before { 7 display: inline-block; 8 vertical-align: middle; 9 width: 0;10 height: 100%;11 visibility: hidden;12 content: '';13 }14 15 .demo span {16 display: inline-block;17 vertical-align: middle;18 }
Now I think of this.