日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

如何讓css文本元素居中

作者:翼遙bingo 更新時間: 2022-07-10 編程語言

文本元素如何居中
未知高度元素水平居中、垂直居中的實現方式

文章目錄

        • 1-1 水平居中:text-align:center
        • 1-2 垂直居中:
          • 1-2-1 單行文本:line-height
          • 1-2-2 多行文本垂直居中

1-1 水平居中:text-align:center

該屬性設置文本和img標簽等一些內聯對象(或與之類似的元素)的居中。

1、 特點:

  • text-align的center應用在一個容器上,它只針對容器里面的文字以及容器里面的display為inline或者inline-block的容器,如果里面的容器display為block,則里面的容器的內容不會居中。
  • text-align具有向下傳遞性,會不斷地向子元素傳遞。如果設置一個div,則其子div中的內容也會居中。

2、 例子

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>css 水平居中</title>
    <style>
        .box {
            width: 400px;
            height: 100px;
            background: pink;
            text-align: center;
        }
    </style>
</head>

<body>
    <div class="box">css 水平居中了--文本文字</div>
</body>

</html>

在這里插入圖片描述

1-2 垂直居中:

1-2-1 單行文本:line-height

1、 對于單行文本,我們只需要將文本行高(line-height屬性)和所在區域高度(height)設置一致就可以了

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>css 垂直居中</title>
        <style>
            .box {
                width: 300px;
                height: 300px;
                background: paleturquoise;
                line-height:300px;
            }
        </style>
    </head>
    <body>
        <div class="box">css 垂直居中了--文本文字</div>
    </body>
</html>
1-2-2 多行文本垂直居中

1、 父級元素高度不固定

父級高度不固定的時,高度只能通過內部文本來撐開。所以,我們可以通過設置內填充(padding)的值來使文本看起來垂直居中,只需設置padding-top和padding-bottom的值相等:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>css 垂直居中</title>
        <style>
            .box {
                width: 300px;
                margin: 50px auto;
                background: paleturquoise;
                padding: 50px 20px;
            }
        </style>
    </head>
    <body>
        <div class="box">css 垂直居中了--文本文字,文本文字,文本文字,文本文字,文本文字,文本文字</div>
    </body>
</html>

2、 父級元素高度固定

vertical-align:middle + displsy:table-cell 使文字垂直居中

<!-- 父級元素高度固定 -->
<!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>父級元素高度固定</title>
    <style>
        .box {
            width: 300px;
            height: 300px;
            background-color: red;
            display: table-cell;
            vertical-align: middle;
        }
    </style>
</head>

<body>
    <div class="box">css 垂直居中了--文本文字,文本文字,文本文字,文本文字,文本文字,文本文字。</div>
</body>

</html>

在這里插入圖片描述

  • vertical-align:middle + displsy:table-cell 使單行文字、多行文字都居中
  • 因為table-cell是inline類型,所以會導致原來的塊級元素每個div一行移動到了同一行
  • 需要分列兩行,需要外面額外添加容器對位置進行控制

原文鏈接:https://blog.csdn.net/hannah2233/article/details/125664374

欄目分類
最近更新