HTML(让 div 水平并垂直居中)

本文介绍了五种网页布局技巧:fixed定位的盒1,利用transform居中对齐的盒2,弹性盒布局的盒3,行内块级元素的盒4,以及网格布局的盒5。详细展示了这些方法在响应式设计中的应用和优劣。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

.box1{
        width: 400px;
        height: 400px;
        top: 0;bottom: 0;left: 0;right: 0;
        margin: auto;
        相对于当前窗口
        position: fixed;
        background-color: pink;
    }
<!-- 方法一  上下左右都为0,margin:auto  -->
<div class="box1"></div>
.box2{
        width: 350px;
        height: 350px;
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
        background-color: skyblue;
    }
<!-- 方法二 left和top都为50%,向左、向上平移50% -->
<div class="box2"></div>
.box3{  
        width: 300px;
        height: 300px;
        background-color: salmon;
        position: relative;
        margin: 200px auto;
    } 
<!-- 方法三  弹性盒 -->
<div class="box3"></div>
.box4{
        width: 500px;;
        height: 500px;
        border: 3px solid #000;
        text-align: center;
        line-height: 500px;
    }
.max{
        width: 250px;
        height: 250px;
        background-color: aqua;
        display: inline-block;
        vertical-align: middle;
<!-- 方法四  将div转成行内快 -->
<div class="box4"><div class="max"></div><span></span></div>
    .box5{
        width: 300px;
        height: 300px;
        border: 3px solid #000;
        margin: 200px auto;
        display: grid;
        grid-template-rows: 100px 100px 100px;
        grid-template-columns: 100px 100px 100px;
        grid-template-areas: ". . ." ". a ." " . . . ";
    }
    .min{
        width: 100px;
        height: 100px;
        background-color: blueviolet;
        grid-area: a;
<!-- 方法五  使用网格布局 -->
<div class="box5">
    <div class="min"></div>
</div>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值