html+css 将<div>水平居中与垂直居中的几种办法

示例代码:

<style>
    .box {
        width: 200px;
        height: 200px;
        background-color: red;
    }

    .inner {
        width: 100px;
        height: 100px;
        background-color: white;
    }
</style>
<body>
    <div class="box">
        <div class='inner'>
            居中
        </div>
    </div>
</body>
水平居中

1.<center>标签
最简单的方法,只需要在<div>外加上<center>就可以让<div>水平居中:
代码:

<body>
    <div class="box">
        <center>
            <div class='inner'>
                居中
            </div>
        </center>
    </div>
</body>

效果:
<center>标签水平居中
2.margin法
<div>的 margin (外边距)属性设置成 “0 auto” 就可以居中
代码:

.inner {
    width: 100px;
    height: 100px;
    background-color: white;
    margin: 0 auto;
}

效果:
margin
3.绝对位置法
<div>设置成绝对布局,然后用left或right移动<div>到中间,由于元素的坐标原点是左上角,所以为了居中,要移回半个<div>宽度的距离。
可以用margin-left:[1/2宽度]px或者transform: translate(-50%,0)实现
需要注意的是使用这种方法时,必须定义了位置布局方式。
代码:

.box {
    position: relative;
    width: 200px;
    height: 200px;
    background-color: red;
}

.inner {

    width: 100px;
    height: 100px;
    background-color: white;
    position: absolute;
    left: 50%;
    margin-left: -50px;
}

效果:
绝对布局法

垂直居中

1.margin法
垂直居中也可以用margin实现,同样需要声明布局方式。
代码:

.box {
    position: relative;
    width: 200px;
    height: 200px;
    background-color: red;
}

.inner {
    position: absolute;
    width: 100px;
    height: 100px;
    background-color: white;
    margin: auto;
    top: 0;
    bottom: 0;
}

效果:
margin垂直居中
2.绝对位置法
和水平居中一样 把left改为top即可
代码:

.box {
    position: relative;
    width: 200px;
    height: 200px;
    background-color: red;
}

.inner {
    width: 100px;
    height: 100px;
    background-color: white;
    position: absolute;
    top: 50%;
    margin-top: -50px;
}

效果:
绝对位置垂直居中

同时居中

1.margin法
只需margin:auto; , 然后topleftrightbottom 设置为相同值即可
代码:

.box {
    position: relative;
    width: 200px;
    height: 200px;
    background-color: red;
}

.inner {
    width: 100px;
    height: 100px;
    background-color: white;
    position: absolute;
    margin: auto;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
}

效果:
margin 同时居中
2.绝对位置法
将水平居中垂直居中同时使用即可。
代码:

.box {
    position: relative;
    width: 200px;
    height: 200px;
    background-color: red;
}

.inner {
    width: 100px;
    height: 100px;
    background-color: white;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

效果:
绝对位置同时居中

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值