从前端小白到大佬 定位的盒子如何水平居中、垂直剧中

本文详细介绍了如何使用CSS对绝对定位的元素进行水平和垂直居中,并通过实例展示了轮播图布局的具体实现方法。文章提供了代码示例,帮助读者理解和应用定位技巧。

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

CSS加了定位的盒子如何水平居中、垂直剧中

1.定位盒子的剧中定位的实现
2.案例-轮播图布局

1.绝对定位的盒子居中
要知道加了定位的盒子使用margin:auto来布置盒子居中时无法实现的,需要用到一个小小的算法。
直接用一个例子来说明:
实现效果在这里插入图片描述

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            position: absolute;
            /* 调整水平居中,先左移50%的宽度,在用外边框调整至自身盒子一半的距离,实现居中 */
            left: 50%;
            margin-left: -100px;
            /* 垂直居中同理 */
            top: 50%;
            margin-top: -100px;
            width: 200px;
            height: 200px;
            background-color: thistle;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    </div>

</body>

</html>

相对定位由于是不脱离标准流的,所以可以直接使用margin auto;这个太简单的就不举例子了。

2.案例-轮播图布局
实现效果:
在这里插入图片描述

轮播图.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>轮播图</title>
    <link rel="stylesheet" href="轮播图.css">
</head>

<body>
    <div class="tb-b">
        <img src="imgs/tb.jpg">
        <a href="#" class="left">
            < </a>
                <a href="#" class="right"> > </a>
                <ul class="nav">
                    <li> </li>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li class="last"></li>
                </ul>
    </div>
</body>

</html>

轮播图.css

* {
    margin: 0;
    padding: 0;
}

li {
    list-style: none;
}

.tb-b {
    position: relative;
    margin: 100px auto;
    width: 530px;
    height: 290px;
    background: pink;
    text-align: center;
}

img {
    margin: 5px auto;
}

.left,
.right {
    margin-top: -15px;
    display: block;
    width: 20px;
    height: 30px;
    text-align: center;
    line-height: 30px;
    background-color: rgba(0, 0, 0, 0.3);
    text-decoration: none;
    color: white;
}

.left {
    position: absolute;
    top: 50%;
    left: 5px;
    border-radius: 0 15px 15px 0;
}

.right {
    position: absolute;
    top: 50%;
    left: 505px;
    border-radius: 15px 0 0 15px;
}

.nav {
    position: absolute;
    bottom: 10px;
    left: 50%;
    margin-left: -30px;
    width: 70px;
    height: 13px;
    background-color: rgba(255, 255, 255, 0.3);
    border-radius: 6.5px;
}

li {
    width: 8px;
    height: 8px;
    float: left;
    margin: 3px;
    border-radius: 4px;
    background-color: white;
    text-align: center;
}

ul .last {
    margin-right: 0px;
}

li:hover {
    background-color: tomato;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值