css几种居中方式优缺点,CSS中几种居中方式

1.水平居中的margin:0 auto;

(用于子元素前提是不受float影响)

*{

padding: 0;

margin: 0;

}

.box{

width: 300px;

height: 300px;

border: 3px solid red;

/*text-align: center;*/

}

img{

display: block;

width: 100px;

height: 100px;

margin: 0 auto;

}

![](img1.jpg)

2.水平居中text-align:center;

img的display:block;类似一样在不受float影响下进行,是在父元素上添加效果让它进行水平居中

*{

padding: 0;

margin: 0;

}

.box{

width: 300px;

height: 300px;

border: 3px solid red;

/*text-align: center;*/

}

img{

display: block;

width: 100px;

height: 100px;

margin: 0 auto;

}

3.水平垂直居中(一)定位和需要定位的元素的margin减去宽高的一半

这种方法的局限性在于需要知道需要垂直居中的宽高才能实现,经常使用这种方法

*{

padding: 0;

margin: 0;

}

.box{

width: 300px;

height: 300px;

background:#e9dfc7;

border:1px solid red;

position: relative;

}

img{

width: 100px;

height: 150px;

position: absolute;

top: 50%;

left: 50%;

margin-top: -75px;

margin-left: -50px;

}

4.水平垂直居中(二)定位和margin:auto;

*{

padding: 0;

margin: 0;

}

.box{

width: 300px;

height: 300px;

background:#e9dfc7;

border:1px solid red;

position: relative;

}

img{

width: 100px;

height: 100px;

position: absolute;

top: 0;

left: 0;

right: 0;

bottom: 0;

margin: auto;

}

5.水平垂直居中(三)绝对定位和transfrom

*{

padding: 0;

margin: 0;

}

.box{

width: 300px;

height: 300px;

background:#e9dfc7;

border:1px solid red;

position: relative;

}

img{

width: 100px;

height: 100px;

position: absolute;

top: 50%;

left: 50%;

transform: translate(-50%,-50%);

}

6.水平垂直居中(四)diplay:table-cell

.box{

width: 300px;

height: 300px;

background:#e9dfc7;

border:1px solid red;

display: table-cell;

vertical-align: middle;

text-align: center;

}

img{

width: 100px;

height: 150px;

/*margin: 0 auto;*/  这个也行

}

7.水平垂直居中(五)flexBox居中这个用了C3新特性flex,非常方便快捷,在移动端使用完美,pc端有兼容性问题,以后会成为主流的

.box{

width: 300px;

height: 300px;

background:#e9dfc7;

border:1px solid red;

display: flex;

justify-content: center;

align-items:center;

}

img{

width: 150px;

height: 100px;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值