html盒子自动居中,css盒子怎么居中?

在前端切图的时候,可能经常会遇到一个div盒子怎么在固定区域垂直居中的需求,下面我们来看一下css实现盒子居中的方法。

43956bac3ce15dca6342541d94d50eaf.png

css设置盒子居中的方法:

第一种:

用css的position属性

.div1 {

width: 100px;

height: 100px;

border: 1px solid #000000;

position: relative;

}

.div2 {

width: 40px;

height: 40px;

background-color: red;

position: absolute;

margin: auto;

top: 0;

left: 0;

right: 0;

bottom: 0;

}

第二种:

利用css3的新增属性table-cell, vertical-align:middle;

.div1 {

width: 100px;

height: 100px;

border: 1px solid #000000;

display: table-cell;

vertical-align: middle;

}

.div2 {

width: 40px;

height: 40px;

background-color: red;

margin: auto;

}

第三种:

利用flexbox布局

.div1 {

width: 100px;

height: 100px;

border: 1px solid #000000;

display: flex;

/*!*flex-direction: column;*!可写可不写*/

justify-content: center;

align-items: center;

}

.div2 {

height: 40px;

width: 40px;

background-color: red;

}

第四种:

利用transform的属性(缺点:需要支持Html5)

.div1 {

width: 100px;

height: 100px;

border: 1px solid #000000;

position: relative;

}

.div2 {

height: 40px;

width: 40px;

background-color: red;

position: absolute;

top: 50%;

left: 50%;

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

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

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

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

}

效果图:

fd40ec9273397b1cfcb785a4c2bf8c90.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值