子元素在父元素内居中

水平居中
1.子父元素宽度固定,子元素设置 margin:auto,并且子元素不能设置 浮动,否则居中失效 
2.子父元素宽度固定,父元素设置 text-align:center,子元素设置 display:inline-block,并且子元素不能设置浮动,否则居中失效
    <div class="father">
        <div class="son">

        </div>
    </div>
        .father{
            width: 100px;
            height: 100px;
            border: 1px solid red;
            text-align: center;
        }
        .son{
            width: 50px;
            height: 50px;
            border: 1px solid blue;
            display: inline-block;
            /* margin: auto; */
        }
水平垂直居中
子元素相对于父元素绝对定位,子元素 top,left 设置 50%,子元素 margin-top 和 margin-left 减去各自宽高的一半
    <div class="father">
        <div class="son">

        </div>
    </div>
        .father{
            width: 100px;
            height: 100px;
            border: 1px solid red;
            position: relative;
        }
        .son{
            width: 50px;
            height: 50px;
            border: 1px solid blue;
            position: absolute;
            left: 50%;
            top: 50%;
            margin-left: -25px;
            margin-top: -25px;
        }
子元素相对于父元素绝对定位,子元素上下左右全为 0,然后设置子元素 margin:auto
        .father{
            width: 100px;
            height: 100px;
            border: 1px solid red;
            position: relative;
        }
        .son{
            width: 50px;
            height: 50px;
            border: 1px solid blue;
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            right: 0;
            margin: auto;
        }
子元素相对定位,子元素 top,left 值为 50%,transform:translate (-50%,-50%)
或者 子元素相对父元素绝对定位,子元素 top,left 值为 50%,transform: translate(-50%,-50%)
        .father{
            width: 100px;
            height: 100px;
            border: 1px solid red;
        }
        .son{
            width: 50px;
            height: 50px;
            border: 1px solid blue;
            position: relative;
            left: 50%;
            top: 50%;
            transform: translate(-50%,-50%);
        }
父元素设置弹性盒子, display:flex; justfy-content:center ;align-item:center;
        .father{
            width: 100px;
            height: 100px;
            border: 1px solid red;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .son{
            width: 50px;
            height: 50px;
            border: 1px solid blue;
        }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值