前端面试题001(CSS的居中方式)

本文详细介绍了三种常见的CSS居中方法,包括使用margin: auto实现水平居中,absolute定位配合top, left, bottom, right和line-height实现水平垂直居中,以及利用transform: translate实现更灵活的居中效果。适合前端开发者掌握不同的布局手段。

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

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>前端面试题</title>
        <style type="text/css">
            .box1{
                width: 400px;
                height: 300px;
                margin: 0 auto;/* 盒子水平居中 */
                text-align: center;/*文字水平居中*/
                background-color: green;
            }
        </style>
    </head>
    <body>
        <!-- 1.css的居中方式 -->
        <div class="box1">水平居中</div>
    </body>
</html>

1.1水平居中

 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>前端面试题</title>
        <style type="text/css">
            .box2{
                width: 400px;
                height: 300px;
                margin: auto; /* 盒子水平垂直居中 */
                position: absolute;/*绝对定位*/
                top: 0;
                left: 0;
                bottom: 0;
                right: 0;
                text-align: center;/*文字水平居中*/
                line-height: 300px;/*文字垂直居中(将行高与盒子高度相等)*/
                background-color: greenyellow;
            }
        </style>
    </head>
    <body>
        <!-- 1.css的居中方式 -->
        <div class="box2">水平垂直居中</div>
    </body>
</html>

1.2水平垂直居中

 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>前端面试题</title>
        <style type="text/css">
            .box3{
                width: 400px;
                height: 300px;
                position: absolute;/*绝对定位*/
                top: 50%;
                left: 50%;
                /* margin: -150px 0 0 -200px;*/ /* 盒子水平垂直居中 将盒子的中心点移到屏幕的中心点*/
                transform: translate(-50%,-50%);/*效果同上*/
                text-align: center;/*文字水平居中*/
                line-height: 300px;/*文字垂直居中(将行高与盒子高度相等)*/
                background-color: blue;
            }
        </style>
    </head>
    <body>
        <!-- 1.css的居中方式 -->
        <!-- <div class="box1">水平居中</div> -->
        <!-- <div class="box2">水平垂直居中</div> -->
        <div class="box3">水平垂直居中</div>
    </body>
</html>

1.3水平垂直居中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值