1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > div盒子水平垂直居中的几种方式

div盒子水平垂直居中的几种方式

时间:2022-12-02 13:32:20

相关推荐

div盒子水平垂直居中的几种方式

1. div水平居中

div{width:100px;height:100px;margin:0 auto;}

2. div水平垂直居中

这里要有两层或者给body设置高度100vh,然后给元素设置绝对定位,并且left、right、top、bottom全为0,margin:auto就能实现div水平垂直居中了

<!-- <div class="out"><div class="box">test</div></div> --><div class="box">test</div><style>*{margin: 0;padding: 0;}body{height:100vh;}.box{border:1px solid red;height: 80px;width:80px;position: absolute;left: 0;bottom: 0;right: 0;top: 0;margin:auto;} </style>

3. 使用table-cell实现div水平垂直居中

table-cell:块级表格元素

将父盒子设置为table-cell元素,可以使用text-align:center和vertical-align:middle实现水平、垂直居中。

子元素设置为inline-block

<!DOCTYPE html><html lang='cn'><head><meta charset='UTF-8'><meta http-equiv='X-UA-Compatible' content='IE=edge'><meta name='viewport' content='width=device-width, initial-scale=1.0'><title>Document</title><style>*{margin: 0;padding: 0;}.out{display:table-cell;text-align: center;vertical-align: middle;width:100vw;height:100vh;}.box{border:1px solid red;height: 80px;width:80px;display: inline-block;} </style></head><body><div class="out"><div class="box">test</div></div></body><script></script></html>

4. 使用弹性布局

使用弹性布局居中要给父元素加上高度才会垂直居中

<!DOCTYPE html><html lang='cn'><head><meta charset='UTF-8'><meta http-equiv='X-UA-Compatible' content='IE=edge'><meta name='viewport' content='width=device-width, initial-scale=1.0'><title>Document</title><style>*{padding: 0;margin: 0;}.out{display: flex;justify-content: center;align-items: center;height: 100vh;}.test{width: 100px;height:100px;border:1px solid red;}</style></head><body><div class="out"><div class="test">test</div></div></body><script></script></html>

5. 子绝父相定位居中

left、top各50%,margin-left、margin-top是宽高的一半并且使用负数

<!DOCTYPE html><html lang='cn'><head><meta charset='UTF-8'><meta http-equiv='X-UA-Compatible' content='IE=edge'><meta name='viewport' content='width=device-width, initial-scale=1.0'><title>Document</title><style>*{padding: 0;margin: 0;}.out{position:relative;height: 100vh;}.test{width: 100px;height:100px;position:absolute;top:50%;left:50%;margin-left:-50px;margin-top:-50px;border:1px solid red;}</style></head><body><div class="out"><div class="test">test</div></div></body><script></script></html>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。