行内元素与块级元素的水平垂直居中

行内元素与块级元素的水平垂直居中,有很多种方式,以下是我喜欢用的方式;

一、 水平居中
行内元素

.parent {
        text-align: center;
      }

块级元素
margin方式:

.son {
        margin: 0 auto;
      }

flex布局

.parent {
        display: flex;
        justify-content: center;
      }

绝对定位

 .son {
        position: absolute;
        left: 50%;
        transform: translate(-50%, 0);
      }

二、垂直居中
行内元素

.parent {
        height: 高度;
      }
      .son {
        line-height: 高度;
      }
      /* 注:① 子元素 line-height 值为父元素 height 值。② 单行文本。 */

块级元素
flex弹性盒子

 .parent {
        display: flex;
        align-items: center;
      }

绝对定位

.son {
        position: absolute;
        top: 50%;
        transform: translate(0, -50%);
      }

小案例:
盒子box1里面的盒子box2,需要水平居中;
box2中的文字,需要水平垂直居中;

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>fish</title>
    <style type="text/css">
      .box1 {
        background-color: #cbedee;
        padding: 30px 0;
      }
      .box2 {
        width: 750px;
        height: 100px;
        /* 设置margin: 0 auto是让box2垂直水平居中 */
        margin: 0 auto;
        background: linear-gradient(180deg, #ffce82, #ffa15a);
        border-radius: 50px;
        box-shadow: 0px 6px 10px 0px #d63d00, 0px 6px 0px 0px #ff7848,
          0px 2px 0px 0px #ffffff inset;
        /* box2中的文字 */
        font-size: 36px;
        font-weight: bold;
        color: #fff;
        text-shadow: 0px 2px 4px 0px #bd2e00;
        /* 调节文字的水平垂直居中,方法一 */
        /* text-align: center;
        line-height: 100px; */

        /* 调节文字的水平垂直居中,方法一 */
        display: flex;
        align-items: center;
        justify-content: center;
      }
    </style>
  </head>

  <body>
    <div class="box1">
      <div class="box2">服务电话:400-123-456</div>
    </div>
    <script></script>
  </body>
</html>

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值