实现盒子水平垂直居中

本文详细介绍了在网页布局中使盒子水平垂直居中的四种常见方法:1) 利用文本居中和行高;2) 利用定位和外边距;3) 利用定位和CSS平移;4) 利用Flex布局。通过实例代码展示每种方法的具体实现步骤,帮助开发者更好地理解和应用这些技巧。
摘要由CSDN通过智能技术生成


实现的效果如下
在这里插入图片描述

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

1、利用文本居中和行高实现

给父盒子设置文本居中text-align:center和行高line-height
将子盒子转为行内块元素,并设置vertical-align:middle

<style>
      .father {
        width: 300px;
        height: 300px;
        background-color: aqua;
        text-align: center;
        line-height: 300px;
      }
      .son {
        width: 100px;
        height: 100px;
        background-color: pink;
        display: inline-block;
        vertical-align: middle;
      }
    </style>

2、利用定位+外边距

利用子绝父相
1、给子盒子设置四个方向的位移均为0,外边距margin设为auto

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

2、给子盒子设置top:50% left:50% 让子盒子相距父盒子上边界,左边界宽高的50%
再利用 margin-top margin-left返回子盒子自身宽高的50%

.father {
        width: 300px;
        height: 300px;
        background-color: aqua;
        position: relative;
      }
      .son {
        width: 100px;
        height: 100px;
        background-color: pink;
        position: absolute;
        /* 父盒子高度的一半 */
        top: 50%;
        left: 50%;
        /* 自身高度的一半 */
        margin-top: -50px;
        margin-left: -50px;
      }

3、利用定位+平移

利用子绝父相,给子盒子设置top和left移动父盒子宽高的50%,再利用平移,返回自身宽高的50%

.father {
        width: 300px;
        height: 300px;
        background-color: aqua;
        position: relative;
      }
      .son {
        width: 100px;
        height: 100px;
        background-color: pink;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }

4、利用flex布局

给父盒子设置display:flex,justify-content:center(主轴居中)、align-items:center(交叉轴居中)

.father {
	  width: 300px;
	  height: 300px;
	  background-color: aqua;
	  display: flex;
	  justify-content: center;
	  align-items: center;
	}
	.son {
	  width: 100px;
	  height: 100px;
	  background-color: pink;
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值