2020-08-07

1. 水平居中

(1)行内元素居中

父元素设置 text-align:center
示例代码:

<body>
    <div class="parent">
        <span class="son">sss</span>
    </div>
</body>
<style>
    .parent{
        width: 500px;
        height: 300px;
        background-color: blueviolet;
    }
    .son {
        width: 100px;
        height: 100px;
        background-color: yellow;      
    }
</style>
<style>
    .parent{
        text-align: center;
    }
    /* .son{
        display: inline-block;
    } */
</style>

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

(2)块级元素居中

子元素: margin: 0 auto
代码:

<body>
    <div class="parent">
        <div class="son">sss</div>
    </div>
</body>
<style>
    .parent{
        width: 500px;
        height: 300px;
        background-color: blueviolet;
    }
    .son {
        width: 100px;
        height: 100px;
        background-color: yellow;      
    }
</style>
<style>
    .parent{
        text-align: center;
    }
    .son{
        margin: 0 auto;
    }
</style>

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


请问:为什么 margin:auto 0;不能实现水平居中。
答:子元素宽度会默认占满父元素一行,而高度不会。

如下;
子元素宽度没有值时,默认占满一行;

<body>
    <div class="parent">
        <div class="son">sss</div>
    </div>
</body>
<style>
    .parent{
        width: 500px;
        height: 300px;
        background-color: blueviolet;
    }
    .son {
        /* width: 100px; */
        height: 100px;
        background-color: yellow;      
    }
</style>
<style>
    .parent{
        text-align: center;
    }
    /* .son{
        margin: 0 auto;
    } */
</style>

效果图:
在这里插入图片描述
子元素高度不设置值时,高度为自身内容高度。

<body>
    <div class="parent">
        <div class="son">sss</div>
    </div>
</body>
<style>
    .parent{
        width: 500px;
        height: 300px;
        background-color: blueviolet;
    }
    .son {
        width: 100px;
        /* height: 100px; */
        background-color: yellow;      
    }
</style>
<style>
    .parent{
        text-align: center;
    }
    /* .son{
        margin: 0 auto;
    } */
</style>

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值