css实现块级元素水垂直居中的方法
- 父级:text-align:center+line-height:center
- 父元素:display:table-cell;vertical-align:middle;text-align:center;
子元素:display:inline-block
- 父元素:vertical-align:middle;display:table-cell;
子元素:display:table;margin:0 auto;
- 父级给相对定位,子级绝对定位,margi:auto,上下左右值设为0
- 父级相对定位,子级绝对 设置left和top为50%,再向左和向上移动负的子级一半
- 父级:display:flex;侧轴,主轴居中 justify-content:center;align-items:center
- 父级:display:flex,子级:margin:auto
1.父级:text-align:center+line-height:center
.f10{ text-align: center; line-height: 100px; } <div class="case-box f10" data-case="f10"> <div class="test" style="background-color: lightblue;width: 200px;">测试文字</div> </div>
2.父元素:display:table-cell;vertical-align:middle;text-align:center;
子元素:display:inline-block
.f11 .parent{ display: table-cell; text-align: center; vertical-align: middle; } .f11 .child{ width: 80px; display: inline-block } <div class="case-box f11" data-case="f11"> <div class="parent" style="background-color: gray; width:200px; height:100px;"> <div class="child" style="background-color: lightblue;">测试文字</div> </div> </div>
3.父元素:vertical-align:middle;display:table-cell;
子元素:display:table;margin:0 auto;
.f13 .parent{ display:table-cell; vertical-align:middle; } .f13 .child{ display: table; margin: 0 auto; } <div class="case-box f13" data-case="f13"> <div class="parent" style="background-color: lightgray; width:200px; height:100px; "> <div class="child" style="background-color: lightblue;">测试文字</div> </div> </div>
4.父级给相对定位,子级绝对定位,margi:auto,上下左右值设为0
.f14 .parent{ position: relative; } .f14 .child{ position:absolute; top:0; left:0; right:0; bottom: 0; height: 50px; width: 80px; margin: auto; } <div class="case-box f14" data-case="f14"> <div class="parent" style="background-color: lightgray; width:200px; height:100px; "> <div class="child" style="background-color: lightblue;">测试文字</div> </div> </div>
5.父级相对定位,子级绝对 设置left和top为50%,再向左和向上移动负的子级一半
.f15 .parent{ position: relative; } .f15 .child{ position: absolute; top:50%; left:50%; transform:translate(-50%,-50%) } <div class="case-box f15" data-case="f15"> <div class="parent" style="background-color: lightgray; width:200px; height:100px; "> <div class="child" style="background-color: lightblue;">测试文字</div> </div> </div>
6.父级:display:flex;侧轴,主轴居中 justify-content:center;align-items:center
.f17 .parent{ display:flex; justify-content: center; align-items:center; } <div class="case-box f17" data-case="f17"> <div class="parent" style="background-color: lightgray; width:200px; height:100px; "> <div class="child" style="background-color: lightblue;">测试文字</div> </div> </div>
7.父级:display:flex,子级:margin:auto
.f16 .parent{ display: flex; } .f16 .child{ margin: auto; } <div class="case-box f16" data-case="f16"> <div class="parent" style="background-color: lightgray; width:200px; height:100px; "> <div class="child" style="background-color: lightblue;">测试文字</div> </div> </div>