CSS常见水平垂直居中的总结

本文介绍了多种CSS布局中实现元素水平垂直居中的方法,包括已知宽高、未知宽高及父级高度确定的情况下的解决方案,并针对不同场景提供了具体实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.最常见的水平居中的方法:

1.margin:0 auto;

2.text-align:center;

二.

1.已知宽高的水平垂直居中

法一:.center{
        width:200px;
        height: 200px;
        background: pink;
        position: absolute;
        top:50%;
        left: 50%;
        margin-left: -100px;
        margin-top:-100px;
     }
法二:.center{
          width:200px;
          height: 200px;
          background: pink;
          position:absolute;
          left:0;
          top: 0;
          bottom: 0;
          right: 0;
          margin: auto;
      }
法三:.box {
        display: table-cell;
        vertical-align: middle;
        text-align: center;
        width: 500px;
        height: 500px;
        border: 1px solid #ccc;
    }
			
      img {
        max-height: 480px;
        max-width: 400px;
        vertical-align: middle;
    }

 

2.未知宽高的水平垂直(IE8以上可以使用) 

 

<div class="center"></div>
.center{
    background: pink;
    position: absolute;
    top:50%;
    left: 50%;
    transform: translate(-50%,-50%);
}

3.父级高度确定的水平垂直居中

<div class="wrap">
    <div class="center"></div>
</div>

 

.wrap {
    display: flex;
    height: 300px;
    background: #ccc;}
.wrap .center { 
    width: 100px;
    height: 100px;
    margin: auto;
    background: #ddd;
} 

4.图片的垂直居中

<div class="center">
    <a><img src="images/temp.png" /> </a>
</div>
.center{
    display:table;/*若不想要独占一行,可以改为display:inline-table; */
}
.center a{
    display:table-cell;
    vertical-align:middle;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值