zoukankan      html  css  js  c++  java
  • css文字上下居中,一行文字居中,两行或多行文字同样居中

    附图:

    1. 利用Flex布局实现

    demo.html

    1 <div class="demo demo-flex"><span>孤云将野鹤,岂向人间住。莫买沃洲山,时人已知处。</span></div>

    style.css

     1 .demo {
     2          120px;
     3         height: 200px;
     4         border: 1px solid red;
     5         /*line-height: 25px;*/
     6         font-size: 12px;
     7       }
     8       .demo-flex{
     9         display: flex;
    10         align-items: center;
    11         justify-content: center;
    12         flex-direction: column;
    13       }

    2. 利用属性 line-height

    <div id="box">
      <span>文本上下居中</span>
    </div>

    style.css

    1 #box {
    2        200px;
    3       height: 120px;
    4       border: 1px solid red;
    5       text-align: center;
    6  }
    7 #box span {
    8       line-height: 120px;
    9 }

    注意: 这个方法只适用于 单行文本

    3. 利用position 定位来实现

     html

    1 <div class="box">
    2     <a class="remind">春宵一刻值千金,花有清香月有阴。歌管楼台声细细,秋千院落夜沉沉。</a>
    4 </div>

    css

     1 .box{
     2    500px;
     3 
     4   height: 500px;
     5 
     6   border: 1px solid red;
     7 
     8   text-align: center;
     9 }
    10 
    11 定位方法 (一)
    12 
    13 .remind {
    14   position: absolute;
    15   top: 50%;
    16   left: 50%;
    17   transform: translate(-50%, -50%);
    18 }
    19 
    20 定位方法 (二)
    21 
    22 .remind {
    23   position: absolute;
    24   top: 0;
    25   left: 0;
    26   right: 0;
    27   bottom: 0;
    28   margin: auto 0;
    29   height: 0;
    30 }

    4. 利用 vertical-align 来实现

    即在父容器内放一个100%高度的伪元素,让文本和伪元素垂直对齐,从而达到垂直居中的目的。

    1     <div id="box">
    2       <span>两个黄鹂鸣翠柳</span>
    3     </div>

    css

     1 #box {
     2    200px;
     3   height: 120px;
     4   border: 1px solid red;
     5   text-align: center;
     6    7 }
     8 #box::before {    //    伪元素
     9   content: " ";
    10   display: inline-block;
    11   height: 100%;
    12    1%;
    13   vertical-align: middle;
    14 }
    15 #box span {
    16   vertical-align: middle;
    17 }

    5. 利用 Flex布局 来实现

    1 <div id="box">
    2    <span>两个黄鹂鸣翠柳</span>
    3 </div>

    css

    1 #box {
    2          200px;
    3         height: 120px;
    4         border: 1px solid red;
    5         /*text-align: center;*/
    6         display: flex;
    7         align-items: center;
    8         justify-content: center;
    9       }
  • 相关阅读:
    ASP.NET面试题(二)
    iBatis.Net系列(四) iBatisNet API基础
    ibatisnet系列(一) 总览
    iBatisnet系列(二) 配置运行环境和日志处理
    HDU 1575 Tr A (矩阵乘法)
    HDU 连连看
    1504: ZZ的橱柜 (优先队列)
    离散化思想
    POJ 2777 Count Color (线段树)
    POJ 1823 Hotel (线段树)
  • 原文地址:https://www.cnblogs.com/gaoht/p/9132612.html
Copyright © 2011-2022 走看看