几种我常用的元素居中总结

table-cell 

支持响应式,水平垂直居中

text-align:center 这个只能对行内元素进行水平居中,比如图片,文字,按钮,但是IE 6,7可以对任何元素居中

<div style="border:1px solid red;width: 400px;height: 600px display:table-cell;text-align:center;vertical-align:middle"  >
  <div style="border:1px solid blue;width: 200px;height: 400px;display:inline-block"></div> 
</div>

line-height

如果只有一行文字,并且不多的情况下用,水平垂直居中

 
<div style="border:1px solid blue;width: 200px;height: 400px;line-height=400px" >hihihhhhhhhhhhhhhhhhh</div>
  
</div>


margin 0 auto 加宽度

水平居中,利用margin自动计算,但是对于浮动和绝对定位元素无效
<div style="border:1px solid red;width: 400px;height: 600px"  >
  <div style="border:1px solid blue;width: 200px;height: 400px;margin:0 auto></div> 
</div>
    

绝对定位居中

父元素设置relative,子元素设absolute,同时上下左右设为0,margin设为auto ,要定义高宽

element.style {--父元素
    position: relative;
    border: 1px solid red;
    width: 400px;
    height: 600px;
}

element.style {--子元素
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    border: 1px solid blue;
    width: 200px;
    height: 400px;
}

我是有多懒。。。。

看网上还有一种方法,利用margin负值,看张鑫旭老师的课,有很多用途啊,随后笔记上。。。
element.style {--父元素
    position: relative;
    border: 1px solid red;
    width: 400px;
    height: 600px;
}<pre name="code" class="html">element.style {--子元素
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -100px;
    margin-top: -200px;
    border: 1px solid blue;
    width: 200px;
    height: 400px;

 
 
还有盒式布局,但是我试了没有生效,支持的不是很好,先总结这么多吧~


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值