居中垂直方法

1、行内联元素或文字在父级中水平垂直居中的方法
/* 水平居中 / :text-align: center;
/
垂直居中 */:line-height: 200px;


<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    .d1 {
      width: 400px;
      height: 200px;
      /* 水平居中 */
      text-align: center;
      /* 垂直居中 */
      line-height: 200px;
      background-color: yellow;
    }
    .d1 span {
      background-color: red;
    }
  </style>
</head>
<body>
  <!-- 一行内联元素或文字在父级中水平垂直居中的方法 -->
  <div class="d1">
    <span>内联元素居中</span>
  </div>
</body>
</html>

2、块级元素在父级中水平垂直居中的方法:
2.1、在父级设置相对定位,子级设置绝对定位


<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    .d2 {
      width: 400px;
      height: 200px;
      background-color: blue;
      position: relative;
    }
    .d2 div {
      width: 120px;
      height: 100px;
      background-color: greenyellow;
      /* 定位在父元素中 */
      position: absolute;
      top:50%;
      /* 回调子元素高度的一半 */
      margin-top: -50px;
      left: 50%;
      /* 回调子元素宽度的一半 */
      margin-left: -60px;
    }
  </style>
</head>
<body>
  <!-- 块级元素在父级中水平垂直居中的方法 -->
  <div class="d2">
    <div>块级元素居中</div>
  </div>
</body>
</html>

2.2、也可使用transform的translate属性
transform:translate(-50%,-50%);

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    .d2 {
      width: 400px;
      height: 200px;
      background-color: blue;
      position: relative;
    }
    .d2 div {
      width: 120px;
      height: 100px;
      background-color: greenyellow;
      /* 定位在父元素中 */
      position: absolute;
      top:50%;
      left: 50%;
      transform: translate(-50%,-50%);
    }
  </style>
</head>
<body>
  <!-- 块级元素在父级中水平垂直居中的方法 -->
  <div class="d2">
    <div>块级元素居中</div>
  </div>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值