居中的html样式,CSS实现居中样式

水平居中

行内元素水平居中

方法:用text-align:center实现

html代码部分

行内元素水平居中

css代码部分

.box1{

width: 200px;

height: 200px;

background: tomato;

text-align: center;

}

块元素样式水平居中

方法一:子元素利用margin: 0 auto;实现水平居中

html代码部分

块元素水平居中

css代码部分

.box2{

width: 200px;

height: 200px;

background: tomato;

}

.boy2{

width: 100px;

height: 100px;

background: skyblue;

margin: 0 auto;

}

方法二:将子元素变为table,再利用margin实现

html代码部分

块元素水平居中

css代码部分

.box3{

width: 200px;

height: 200px;

background: tomato;

}

.boy3{

width: 100px;

height: 100px;

background: skyblue;

display: table;

margin: 0 auto;

}

方法三:将子元素设置成inline-block,父元素设置为text-align: center

html代码部分

块元素水平居中

css代码部分

.box4{

width: 200px;

height: 200px;

background: tomato;

text-align: center;

}

.boy4{

width: 100px;

height: 100px;

background: skyblue;

display: inline-block;

}

方法四:利用弹性盒实现水平居中

html代码部分

弹性盒水平居中

css代码部分

.box8{

width: 200px;

height: 200px;

background: tomato;

display: flex;

justify-content:center;

}

.boy8{

width: 100px;

height: 100px;

background: skyblue;

}

垂直居中

行内元素垂直居中

方法:设置与高度相同的行高

html代码部分

行内垂直居中

css代码部分

.box5{

width: 200px;

height: 200px;

background: tomato;

line-height: 200px;

}

块元素垂直居中

方法一:父元素设置成table-cell,再用vertical-align:middle

html代码部分

块元素垂直居中

css代码部分

.box6{

width: 200px;

height: 200px;

background: tomato;

display: table-cell;

vertical-align: middle;

}

.boy6{

width: 100px;

height: 100px;

background: skyblue;

}

方法二:弹性盒实现垂直居中

html代码部分

弹性盒块元素垂直居中

css代码部分

.box7{

width: 200px;

height: 200px;

background: tomato;

display: flex;

align-items: center;

}

.boy7{

width: 100px;

height: 100px;

background: skyblue;

}

水平垂直居中

水平居中记一下利用position的实现方法,剩余的有时间再补上吧,嘻嘻嘻。

方法:position设置0加margin的方法

html代码部分

margin,绝对定位和0实现居中

css代码部分

.box9{

width: 200px;

height: 200px;

background: tomato;

position: relative;

}

.boy9{

width: 100px;

height: 100px;

background: skyblue;

margin: auto;

position: absolute;

left: 0; top: 0; right: 0; bottom: 0;

}

后记

CSS居中的方法肯定不止这几种,只是把最常用的写了一下,后面学到其他的会继续补充。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值