请问为什么设置font后P标签里的字就不能水平居中了

来源:2-9 自由编程

慕九州0179892

2022-02-09 10:50:05

<!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>

    <style>

        * {

            margin: 0;

            padding: 0;

        }


        .transition-test1 .test1-box1{

            width: 500px;

            height: 400px;

            margin:40px auto;

            position: relative;

            overflow: hidden;

        }

        .transition-test1 .test1-box1 img{

            width: 500px;

            height: 400px;            

        }

        .transition-test1 .test1-box1 p{

            position: absolute;

            bottom: 0;

            width: 500px;

            height: 80px;    

            line-height: 80px;      

            color: white;

            text-align: center;          

            /* 设置后不能垂直居中??? */  

            /* font:20px/1.5 Arial,"微软雅黑"; */

            background-color:rgba(200, 200, 200, .7);

            transition: opacity 1s ease 0s;

            opacity: 0;

        }

        .transition-test1 .test1-box1:hover p{

            opacity: 1;

        }

    </style>

</head>


<body>

    <!-- /* 动画过渡 */ -->

    <section class="transition-test1">

        <div class="test1-box1">

            <img src="headerimages/duck.png" alt="">

            <p>这是一只小黄鸭</p>

        </div>

    </section>

</body>


</html>


写回答

1回答

好帮手慕久久

2022-02-09

同学你好,font属性连写中是包含行高的:

https://img.mukewang.com/climg/62032d0d097465d205190094.jpg

该行高会覆盖写在它上面的line-height属性:

https://img.mukewang.com/climg/62032d4409f050a707430249.jpg

导致文字实际的行高与height属性不相等,所以无法垂直居中。

建议将font属性写在line-height上面,例如:

https://img.mukewang.com/climg/62032dae0995ad1f07510450.jpg

另外,font连写时,一般会使用默认行高,代码还可以如下这样写:

https://img.mukewang.com/climg/62032e17097d4d0f06430275.jpg

当然,还可以直接在font中设置行高:

https://img.mukewang.com/climg/62032e9d09f2e8e707250382.jpg

祝学习愉快!

0

0 学习 · 15276 问题

查看课程