CSS+div => 水平居中、垂直居中、水平垂直居中

本文详细介绍了使用CSS实现元素在父容器中水平居中、垂直居中及同时水平垂直居中的多种方法,包括flex布局、定位及table-cell等,适合初学者及需要复习相关知识点的前端开发者。

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

HTML代码

<div class="father">
   <div class="son"></div>
</div>

CSS代码

.father {
    width: 500px;
    height: 300px;
    background-color: lightskyblue;
}

.son {
    width: 100px;
    height: 100px;
    background-color: lightgreen;
}

初始效果
在这里插入图片描述


以下代码都是基于上面代码添加

A => 水平居中

效果预览
在这里插入图片描述

  1. flex方式
.father {
    display: flex;
    justify-content: center;
}
  1. 定位 + left方式(已知宽度可以用margin-left, 未知宽度用transform)
.father {
    position: relative; /*想知道为什么加这一句,去掉看son对谁居中就知道了*/
}
.son {
    position: absolute;
    left: 50%;
    margin-left: -50px; /* 已知宽度 */
    /*transform: translateX(-50%);/* 未知宽度,这里的50%是参考自身实际宽度 */
}
  1. margin auto方式
.son {
    margin: 0 auto;
}

B => 垂直居中

效果预览
在这里插入图片描述

  1. flex方式
.father {
    display: flex;
    align-items: center;
}
  1. 定位 + top方式(已知、未知宽度同理)
.father {
    position: relative;
}
.son {
    position: absolute;
    top: 50%;
    margin-top: -50px;
    /*transform: translateY(-50%);*/
}
  1. table-cell + vertical-align方式
.father {
    display: table-cell;
    vertical-align: middle;
}

C => 水平垂直居中

效果预览
在这里插入图片描述

  1. flex方式
.father {
    display: flex;
    justify-content: center;
    align-items: center;
}
  1. 定位 + top left方式(已知、未知宽度同理)
.father {
    position: relative;
}

.son {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;
/*transform: translate(-50%,-50%);*/
}
  1. table-cell + vertical-align + margin auto方式
.father {
    display: table-cell;
    vertical-align: middle;
}

.son {
    margin: auto;
}

吃完东西擦嘴,学完东西总结

如果不考虑兼容性,那就用flex吧,其次,定位的方式也常用,table-cell比较冷门,多一条后路
跟我念:flex、定位、table-cell … flex、定位、table-cell

什么?不够,那继续看这个吧 >> 何居中一个元素(终结版)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值