css水平垂直居中方法归纳总结

css水平垂直居中方法归纳总结

行级元素

单行文字水平垂直居中

html

<div>我要居中</div>

css

div{
    width: 100px;
    height: 100px;
    background-color: yellow;
    text-align: center;
    line-height: 100px;
}

块级元素

已知宽高(使用定位)

1.使用margin移动

定位之后使用margin-left移动子级宽度的一半,使用margin-top移动子级高度的一半

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
.father{
    width: 500px;
    height: 500px;
    border: 1px solid yellow;
    position: relative;
}
.son{
    width: 100px;
    height: 100px;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -50px;
    margin-top: -50px;
    background-color: green;
}
   
</style>
<body>
    <div class="father">
        <div class="son"></div>
    </div>
</body>
</html>
2.使用margin:auto

html

<div class="father">
        <div class="son"></div>
    </div>

css

.father{
    width: 500px;
    height: 500px;
    border: 1px solid yellow;
    position: relative;
}
.son{
    width: 100px;
    height: 100px;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    background-color: green;
}

未知宽高

1.使用translate方法移动居中

html

<div class="father">
        <div class="son">
            <div style="width: 100px; height: 100px;background-color: green;"></div>
        </div>
</div>

css

.father{
    width: 500px;
    height: 500px;
    border: 1px solid yellow;
    position: relative;
}
.son{
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%)
}
2.使用flex布局居中

html

<div class="father">
        <div class="son">
            <div style="width: 100px; height: 100px;background-color: green;"></div>
        </div>
</div>

css

.father{
    width: 500px;
    height: 500px;
    border: 1px solid yellow;
    display: flex;
    justify-content: center;
    align-items: center;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值