CSS水平居中与垂直居中

一、水平垂直居中的通用方法
  1. flex布局
    设置父元素的display属性为flex,并设置主轴(justify-content)和交叉轴(align-items)上的对齐方式为center即可。
<html>
<head>
  <style>
    .father {
      width: 200px;
      height: 200px;
      background-color: indianred;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .son {
      width: 50px;
      height: 50px;
      background-color: whitesmoke;
    }
  </style>
</head>
<body>
<div class="father">
  <div class="son"></div>
</div>
</body>
</html>

:flex布局学习指路:Flex布局教程:语法篇.

  1. 绝对定位+transform属性
    父元素的position属性设置为相对定位(relative),子元素设置为绝对定位(absolute)
    ②使子元素距离top50%(相对于父元素),距离left50%(相对于父元素)
    ③利用transform属性定义子元素的2D转换,分别在x轴和y轴上各平移-50%(相对于子元素本身)
<html>
<head>
  <style>
    .father {
      width: 200px;
      height: 200px;
      background-color: indianred;
      position: relative;
    }

    .son {
      width: 50px;
      height: 50px;
      background-color: whitesmoke;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  </style>
</head>
<body>
<div class="father">
  <div class="son"></div>
</div>
</body>
</html>
二、水平居中
  1. 文字的水平居中(单行&多行)
    只需要设置文字所在容器text-align属性为center即可。
<html>
<head>
  <style>
    .con {
      text-align: center;
    }
  </style>
</head>
<body>
<div class="con">
  文字水平居中
</div>
</body>
</html>
  1. 容器的水平居中
    设置子容器(即要居中的容器)的外边距margin属性为0 auto即可。
    注意:该方法只适用于已知容器宽度的场景。若子容器没有设置width或者设置了width为100%,则将不起作用。此时可以采用flex布局实现水平居中。
<html>
<head>
  <style>
    .father {
      background-color: indianred;
    }

    .son {
      background-color: whitesmoke;
      width: 50px;
      margin: 0 auto;
    }
  </style>
</head>
<body>
<div class="father">
  <div class="son">容器的水平居中</div>
</div>
</body>
</html>
三、垂直居中
  1. 单行文字垂直居中
    设置文字所在容器height等于line-height即可。
<html>
<head>
  <style>
    .con {
      height: 100px;
      line-height: 100px;
      background-color: yellowgreen;
    }
  </style>
</head>
<body>
<div class="con">
  单行文字垂直居中
</div>
</body>
</html>
  1. 多行文字垂直居中
    设置文字所在容器的内边距padding即可,例:30px 0
    :此方法同样适用于单行文字的垂直居中。
<html>
<head>
  <style>
    .con {
      background-color: indianred;
      padding: 30px 0;
    }
  </style>
</head>
<body>
<div class="con">
  多行文字垂直居中多行文字垂直居中多行文字垂直居中
  多行文字垂直居中多行文字垂直居中多行文字垂直居中
  多行文字垂直居中多行文字垂直居中多行文字垂直居中
</div>
</body>
</html>
  1. 容器的垂直居中
    通用方法去掉水平居中即可,略。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值