css如何让块元素水平垂直居中

css如何让块元素水平垂直居中

  • 在知道父元素的宽高时,通过设置margin-left,margin-right的方式来使子元素居中
  • 使用定位。在知道子元素的宽高时,定位之后通过设置
    left:50%,top:50%,
    margin-left:-xx px,margin-top:-xx px。
    另外一种写法:
    left: calc(50% - xx px);
    top: calc(50% - xx px);
    以下是代码演示:
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        ul {
            list-style: none;
        }

        .box {
            position: absolute;
            width: 200px;
            height: 200px;
            background-color: orange;
            position: absolute;
            /* left: 50%;
            top: 50%;
            margin-left: -100px;
            margin-top: -100px;  */
            /* left: 50% - 100px; 错误写法*/
            /* clac() 可以帮助我们去计算表达式的最终结果 */
            /* 运算符号前后有空格  */
            left: calc(50% - 100px);
            top: calc(50% - 100px);
        }

        .d1{
            width: 100px;
            height: 100px;
            background-color: red;
            /* 设置 margin-left  是 自身宽度的2倍 还多100px */
            margin-left: calc(100px * 2 + 100px);
        }
    </style>
</head>

<body>
    <div class="box"></div>

    <div class="d1"></div>
</body>

</html>
  • 使用定位。在知道子元素的宽高时,定位之后通过设置
    left:0,top:0,bottom:0,
    right:0,margin:0来使子元素居中
  • 使用定位,在父元素子元素宽高都未知时,定位之后通过设置left:50%,top:50%,transfrom:translate(-50%,-50%)
    需要注意的是:transform:translate中的-50%是子元素的宽度
    以下代码演示:
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
   <style>
       .box{
           width: 500px;
           height: 500px;
           background-color: aqua;
           position: relative;
       }
       .container{
           width: 250px;
           height: 250px;
           background-color: pink;
           position: absolute;
           left: 50%;
           top: 50%;
           transform: translate(-50%,-50%);
       }
   </style>
</head>
<body>
   <div class="box">
       <div class="container">

       </div>
   </div>
</body>
</html>

效果图:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值