css文字兩端對齊

智雲程式設計發表於2019-01-02

在做表單時我們經常遇到讓上下兩個欄位對齊的情況,比如姓名, 手機號碼, 出生地。這樣我們就要用到 text-align, text-justify樣式了。

text-align直接設為justify就行了,text-justify的情況就複雜了,可能有人對它還不熟悉。IE的取值如下:

  • auto :允許瀏覽器使用者代理確定使用的兩端對齊法則
  • inter-word :透過增加字之間的空格對齊文字。該行為是對齊所有文字行最快的方法。它的兩端對齊行為對段落的最後一行無效
  • newspaper : 透過增加或減少字或字母之間的空格對齊文字。是用於拉丁文字母表兩端對齊的最精確格式
  • distribute :處理空格很像newspaper
  • distribute-all-lines:兩端對齊行的方式與distribute相同,也同樣不包含兩段對齊段落的最後一行。適用於表意字文件
  • inter-ideograph : 為表意字文字提供完全兩端對齊。他增加或減少表意字和詞間的空格

但它最早是作為IE的私有實現,像text-overflow, overflow-x等,在FF很晚才實現,換言之有嚴格的相容性問題。並且FF,chrome需要手動在漢字間插入空白或軟換行標籤才生效,在chrome遇到的阻力就更大了。p>

方案:

    .test1 {
          text-align:justify;
          text-justify:distribute-all-lines;/*ie6-8*/
          text-align-last:justify;/* ie9*/
          -moz-text-align-last:justify;/*ff*/
          -webkit-text-align-last:justify;/*chrome 20+*/
      }
      @media screen and (-webkit-min-device-pixel-ratio:0){/* chrome*/
          .test1:after{
              content:".";
              display: inline-block;
              width:100%;
              overflow:hidden;
              height:0;
          }
      }

執行程式碼:

      
  
    <!DOCTYPE HTML>
    <html>
        <head>
            <title>文字兩端對齊 </title>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    
       
            <style>
        
                .box1{
                    background:red;
                    width:30%;
                }
                .test1 {
                    text-align:justify;
                    text-justify:distribute-all-lines;/*ie6-8*/
                    text-align-last:justify;/* ie9*/
                    -moz-text-align-last:justify;/*ff*/
                    -webkit-text-align-last:justify;/*chrome 20+*/
                }
                @media screen and (-webkit-min-device-pixel-ratio:0){/* chrome*/
                    .test1:after{
                        content:".";
                        display: inline-block;
                        width:100%;
                        overflow:hidden;
                        height:0;
                    }
                }
            </style>
    
        </head>
        <body>
            <div class="box1">
                <div class="test1">姓 名</div>
                <div class="test1">姓 名 姓 名</div>
                <div class="test1">姓 名 名</div>
                <div class="test1">所 在 地</div>
                <div class="test1">工 作 單 位</div>
            </div>
          
    
        </body>
    </html>

這裡推薦一下我的前端學習交流群:731771211,裡面都是學習前端的,如果你想製作酷炫的網頁,想學習程式設計。自己整理了一份2018最全面前端學習資料,從最基礎的HTML+CSS+JS【炫酷特效,遊戲,外掛封裝,設計模式】到移動端HTML5的專案實戰的學習資料都有整理,送給每一位前端小夥伴,有想學習web前端的,或是轉行,或是大學生,還有工作中想提升自己能力的,正在學習的小夥伴歡迎加入學習。

點選:


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69901074/viewspace-2287214/,如需轉載,請註明出處,否則將追究法律責任。

相關文章