CSS布局:水平垂直居中的方式

CSS布局:水平垂直居中的方式

水平垂直居中:元素在水平和垂直方向都居中

在这里插入图片描述

我们常常margin:auto属性控制水平居中,如果想要水平垂直居中,则有以下三类方法。

首先展示html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>css垂直居中</title>
    <style>
        .father{
            background-color: #e80080;
            width: 500px;
            height: 500px;
        }
        .son{
            background-color: #0A98D5;
            width: 200px;
            height: 200px;
        }
    </style>
</head>
<body>
<div class="father">
    <div class="son"></div>
</div>
</body>
</html>

1. 基于定位的水平垂直居中

a. 定宽高的水平垂直居中

第一种实现方式:

.father{
    background-color: #e80080;
    width: 500px;
    height: 500px;
    position: relative;
}
.son{
	background-color: #0A98D5;
    width: 200px;
    height: 200px;
    position: absolute;
    left: 50%;
    top: 50%;
    /* width/2  height/2 */
    margin-left: -100px;
    margin-right: -100px;
}

第二种实现方式:

.father{
    background-color: #e80080;
    width: 500px;
    height: 500px;
    position: relative;
}
.son{
	background-color: #0A98D5;
    width: 200px;
    height: 200px;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
}
b. 不定宽高

该方式不定宽高,div中的内容有多宽/高,就可以根据translate来进行回移

.father{
    background-color: #e80080;
    width: 500px;
    height: 500px;
    position: relative;
}
.son{
	background-color: #0A98D5;
    width: 200px;
    height: 200px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

2. 基于flex弹性盒子

css3中的flex弹性盒子是一种高效地布局盒模型,但是存在一定兼容性,在移动端/微信小程序开发中使用频繁

flex弹性盒子存在两根轴线,通过justify-content和align-items可以进行主轴和交叉轴的对齐

.father{
    background-color: #e80080;
    width: 500px;
    height: 500px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.son{
	background-color: #0A98D5;
    width: 200px;
    height: 200px;
}

3.基于table-cell的水平垂直居中

table-cell原本是用于控制文本的,通过将子div设置为inline or inline-block,并且设置文本居中的属性也能对盒子进行垂直水平居中

注意:此方法一定要求父级有固定宽高

.father{
    background-color: #e80080;
    width: 500px;
    height: 500px;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}
.son{
	background-color: #0A98D5;
    width: 200px;
    height: 200px;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值