CSS五种居中方法 |
您所在的位置:网站首页 › css文字上下对齐怎么设置 › CSS五种居中方法 |
CSS五种居中方法
1.方法一
通过写一个
标签,i标签的高度为百分之百,让i标签的中点和要居中元素的中点处在同一位置
五大居中1
*{margin:0;padding:0;}
.box{width:500px;height:500px;margin:100px auto;border:1px solid #000;
text-align:center;
}
.box .zi{width:200px;height:200px;background:#9f9;
display:inline-block;vertical-align:middle;}
.box i{display:inline-block;height:100%;vertical-align:middle;}
2.方法二 使用定位方法,将需要居中的元素相对其父级定位,然后通过left:0;right:0;top:0;bottom:0;margin:auto;实现居中 五大居中2 *{margin:0;padding:0;} .box{width:500px;height:500px;margin:100px auto;border:1px solid #000; text-align:center;position:relative;} .box .zi{width:200px;height:200px;background:#9f9; position:absolute; left:0;right:0;top:0;bottom:0;margin:auto; }3.方法三 先使用定位,然后将左边的距离设为left:50%-元素自身的宽度/2 上边距设为top:50%-元素自身的高度/2 缺点:当元素大小改变时需要重新计算减去的高度或宽度 五大居中3 *{margin:0;padding:0;} .box{width:500px;height:500px;margin:100px auto;border:1px solid #000; text-align:center;position:relative;} .box .zi{width:200px;height:200px;background:#9f9; position:absolute; left:50%;top:50%;margin:-100px 0 0 -100px; }4.方法四 同样需要用到定位,将需要定位的元素设置为left:50%;top:50%;transform:translate(-50%,-50%); translate(-50%,-50%) 作用是,往上(x轴),左(y轴)移动自身长宽的 50%,以使其居于中心位置 五大居中4 *{margin:0;padding:0;} .box{width:500px;height:500px;margin:100px auto;border:1px solid #000; text-align:center;position:relative;} .box .zi{width:200px;height:200px;background:#9f9; position:absolute; left:50%;top:50%;transform:translate(-50%,-50%); }5.方法五 这个用的是弹性盒中的方法,即display:flex;align-items:center(垂直居中);justify-content:center(水平居中); 五大居中5 *{margin:0;padding:0;} .box{width:500px;height:500px;margin:100px auto;border:1px solid #000; text-align:center;display:flex;align-items:center;justify-content:center;} .box .zi{width:200px;height:200px;background:#9f9;} |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |