liumoc 发表于 2018-8-7 21:38:55

line-height 已经和盒子高度相同了 但是文字并没有垂直居中

line-height 已经和盒子高度相同了 但是文字并没有垂直居中,代码如下 红字部分是有疑问的地方

<!DOCTYPE html>
<html>
<head>
        <meta charset="utf-8">
        <title></title>
        <style type="text/css">
                * {
                        margin: 0px;
                        padding: 0px;
                }
                .search {
                        margin: 15px auto;
                        height: 336px;
                        width: 268px;
                        border: 1px solid #D9E0EE;
                        border-top: 3px solid #FF8400;
                }
                .search h3 {
                        height: 40px;
                        border-bottom: 1px solid #D9E0EE;
                        line-height: 40px;
                        font: 400 16px "微软雅黑";
                }
        </style>
</head>
<body>
        <div class="search">
                <h3>搜索趣图</h3>
        </div>
</body>
</html>

liumoc 发表于 2018-8-7 21:41:39

{:10_266:}

liumoc 发表于 2018-8-7 21:49:04

我刚刚试了下 我把font分开写就没有问题 但是用合写的格式就不会居中 为什么啊{:10_266:}

不二如是 发表于 2018-8-8 09:26:21

本帖最后由 不二如是 于 2018-8-8 10:45 编辑

liumoc 发表于 2018-8-7 21:49
我刚刚试了下 我把font分开写就没有问题 但是用合写的格式就不会居中 为什么啊


1、font元素,在H5中已经不推荐使用,如果需要设置字体大小样式,建议:
font-weight: 400;
            font-size: 16px;
            font-family:"微软雅黑";

并且h3元素已有默认大小,不建议当文本用,所以请用p元素。

2、关于垂直居中,请参看:私家藏货之@垂直居中。

line-height方法适用于和父元素一样高(336px,而不是40px),例如:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
      #fishc{
            width: 500px;
            height: 500px;
            background: gray;
      }

      #fishc p{
            line-height: 500px;
      text-align: center;
      }
    </style>
</head>
<body>

<div id="fishc">
    <p>搜索趣图</p>
</div>

</body>
</html>


这才是line-height和盒子高度相同。

3、所以需要在添加一层div,用来放需要的40px:
<div class="content">
    <div id="fishc">
      <p>搜索趣图</p>
    </div>
</div>

设置行高后,还需要margin需要反向移动负的一半行高:
.content{
            margin: 15px auto;
            height: 336px;
            width: 268px;
            border: 1px solid #D9E0EE;
            border-top: 3px solid #FF8400;
      }
      #fishc{
            margin: -20px 0;
            width: 100%;
            height: 40px;
            border-bottom: 1px solid #D9E0EE;
      }

      #fishc p{
            line-height: 40px;
      text-align: center;
      }


源码(VIP免费):
页: [1]
查看完整版本: line-height 已经和盒子高度相同了 但是文字并没有垂直居中