html盒子模型 居中,CSS解决盒模型居中的问题

CSS实现盒子模型水平居中、垂直居中、水平垂直居中的多种方法

CSS实现盒子模型水平居中的方法

全局样式

.parent {

color: #FFFFFF;

height: 200px;

width: 200px;

margin: 0 auto;

background-color: #000000;

}

.child {

width: 50px;

height: 50px;

background-color: #26f12d;

}

第一种:margin+width

这种方法适用于已经知道width的盒子,实现起来比较简单

.child {

width: 50px;

margin: 0 auto;

}

第二种:text-align+inline-block

这种方法适用于多种场景(width不固定)

.parent {

text-align:center;

}

.child {

display: inline-block;

}

第三种:float+position

这种方法适用于多种场景(width不固定)

.between {

position: relative;

left: 50%;

float: left;

}

.child {

position: relative;

right: 50%; }

第四种:

这种方法适用于多种场景(width不固定)

.parent {

position: relative;

}

.between {

position: absolute;

left:50%;

}

.child {

position: relative;

right: 50%;

}

第五种:flex

这种方法适用于多种场景(width不固定)

.parent {

display:-webkit-box;

-webkit-box-pack: center;

-webkit-box-orient: horizontal;

}

第六种:fit-content

这种方法适用于多种场景(width不固定)

.between {

width: -webkit-fit-content;

margin: 0 auto;

}

CSS实现盒子模型垂直居中的方法

第一种:position

这种方法适用于已经知道width的盒子

.parent { position:relative;

width: 200px;

height: 200px;

}

.child {

position: absolute;

margin:75px 0;

}

第二种:position+transform

这种方法适用于已经知道width的盒子

.parent { position:relative;

width: 200px;

height: 200px;

}

.child {

position: absolute;

top: 50%;

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

}

第三种:flex布局

这种方法适用于多种场景(width不固定)

.parent {

display: flex;

align-items: center;

}

第四种:table-cell布局

这种方法适用于多种场景(width不固定)

.parent {

display: table;

}

.between {

display: table-cell;

vertical-align: middle;

}

CSS实现盒子模型水平垂直居中方法

第一种:

.parent {

position:relative;

}

.child {

position: absolute;

left: 50%;

top: 50%;

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

}

第二种:

.parent { position:relative;

}

.child {

position: absolute;

top: 0;

bottom: 0;

left: 0;

right: 0;

margin: auto;

}

第三种:

.parent {

position:relative;

}

.child {

position: absolute;

top: 50%;

left: 50%;

margin-top:

-25px; /* 自身 height 的一半 */ margin-left: -25px; /* 自身 width 的一半 */

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值