老师,水平垂直居中的方法有点混淆了

老师,水平垂直居中的方法有点混淆了

HTML部分

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="css/css.css">
</head>

<body>
    <div class="box">
        <a href="#"><img src="./images/btn.png" class="button_left" alt=""></a>  
        <img src="./images/cart.png" class="shopping_right" alt="">
        <span>3</span>
    </div>
</body>

</html>

CSS部分

* {
    margin: 0;
    padding: 0;
}

a {
    text-decoration: none;
}

.box {
    width: 500px;
    height: 100px;
    position: absolute;
    top: 50%;
    margin-top: -50px;
    left: 50%;
    margin-left: -250px;
    background-color: aliceblue;
}


.box .button_left {
    width: 100px;
    height: 50px;
    position: absolute;
    left: 30px;
    top: 50%;
    margin-top: -25px;
}

.box .shopping_right {
    width: 100px;
    height: 70px;
    position: absolute;
    right: 40px;
    top:50%;
    margin-top: -35px;
}

.box span {
    display: block;
    width: 30px;
    height:30px;
    background-color: red;
    text-align: center;
    line-height: 30px;
    border-radius: 50%;
    position: absolute;
    top: 10px;
    right: 25px;
}

老师,现在我会用绝对定位实现盒子在页面中水平垂直居中,比如这个最外面的盒子box就用的这个方法,但最开始我试着用margin:auto auto;发现只能水平居中,并不能水平垂直居中,不知道是代码错了还是理解错了,用margin:0 auto,只实现盒子水平居中我倒是能理解,难道只有绝对定位实现盒子在页面水平垂直居中吗?谢谢!

正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

1回答
好帮手慕久久 2022-11-02 18:34:08

同学你好,解答如下:

1、如果不使用定位,直接用margin,只能实现水平居中,无法实现垂直居中:

https://img1.sycdn.imooc.com//climg/6362472109171cba05440338.jpg

2、如果借助定位,则margin可以实现水平垂直居中。比如:

https://img1.sycdn.imooc.com//climg/6362475d09e6b5e605710456.jpg

此处内容属于拓展,可以看看。

3、不只是绝对定位的盒子能水平、垂直居中,固定定位也可以,可以自己写个demo试试。

祝学习愉快!

问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师