CSS水平垂直居中的几种实现方式

本文详细介绍了五种在CSS中实现元素水平垂直居中的方法,包括使用`position:absolute`配合`margin`或`transform`,利用`margin:auto`,使用弹性盒子以及结合文本对齐和行高。这些技巧涵盖了不同场景下的居中需求,适用于静态布局和响应式设计。
摘要由CSDN通过智能技术生成

1.利用 position:absolute

<div class="father">
     <div class="son"></div>
</div>
  1. 已知元素宽度和高度时,可以设置position: absolutemargin为负的宽高的一半
<style>
    .father{
        position: relative;
        background-color: pink;
        width: 200px;
        height: 200px;
    }
    .son{
        position: absolute;
        background-color: red;
        width:50px;
        height: 50px;
        left: 50%;
        top: 50%;
        margin-top: -25px;
        margin-left: -25px;
    }
</style>
  1. 当元素宽度和高度未知时,可以设置position: absolutetransform: translate(-50%, -50%)
.father{
        position: relative;
        background-color: pink;
        width: 200px;
        height: 200px;
    }
    .son{
        position: absolute;
        width: 50px;
        height: 50px;
        background-color: red;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-50%);
    }

2. 利用margin:auto

.father{
        position: relative;
        background-color: pink;
        width: 200px;
        height: 200px;
    }
    .son{
        position: absolute;
        background-color: red;
        width: 50px;
        height: 50px;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        margin: auto;
    }

3. 利用弹性盒子

通过给父元素设置display:flex来实现居中

.father{
        display: flex;
        justify-content: center; //主轴
        align-items: center; //侧轴
        background-color: pink;
        width: 200px;
        height: 200px;
    }
    .son{
        background-color: red;
        width: 50px;
        height: 50px;
    }

在这里插入图片描述

4. 利用水平对齐和行高

设置text-align:centerline-height:height实现单行文本水平垂直居中

<div class="father">
     <div class="son">我要居中</div>
</div>
	.father{
	        background-color: pink;
	        width: 200px;
	        height: 200px;
	        text-align: center;
	}
	.son{
	    line-height: 200px;
	}

在这里插入图片描述

5. 最简便的方法

flex+auto
父元素设置flex 子元素margin:auto;

<style>
    .g-container{
        display: flex;
        width: 300px;
        height: 300px;
        background-color:aqua;
    }
    .g-box{
        margin: auto;
        width: 100px;
        height: 100px;
        background-color: black;
    }
</style>
<body>
    <div class="g-container">
        <div class="g-box"></div>
    </div>
</body>

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值