V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
cheejay
V2EX  ›  HTML

求助各位大佬。。html 文字居中带背景还有更好的方法吗

  •  
  •   cheejay · Apr 8, 2017 · 4536 views
    This topic created in 3308 days ago, the information mentioned may be changed or developed.

    题目要求效果图如下 我现在是这样实现的

    <style> p{ background-color: blue; font-size: 5ex; display: inline-block; margin:0 auto; width: 200px ; } </style> <body>

    我只是想居中带背景而已

    </body>
    可是我总觉得这不是最佳的方案,请问各位大佬还有什么更好的方法吗
    11 replies    2017-04-10 19:54:08 +08:00
    wukongkong
        1
    wukongkong  
       Apr 8, 2017   ❤️ 1
    设置了宽高,不需要设置 display: inline-block;,因为已经把固定了背景的长宽。

    flex 方法,可以研究研究:
    在外面套一层,我这里直接在 body 上面写了:
    ```js
    body{
    //设置 flex 方式
    display: flex;
    //容器内对齐方式
    //垂直居中: align-items: center;
    justify-content: center;
    }

    p{
    background: #ebe4ff;
    }
    ```
    cheejay
        2
    cheejay  
    OP
       Apr 8, 2017 via Android
    @wukongkong 感谢,但是似乎老版本例如 IE10 以下都不支持这种方式……
    bdbai
        3
    bdbai  
       Apr 8, 2017 via Android   ❤️ 1
    用 display table 和 table-cell 组合居中
    wukongkong
        4
    wukongkong  
       Apr 8, 2017 via Android
    @cheejay 让他们升级浏览器 笑哭😂
    est
        5
    est  
       Apr 8, 2017   ❤️ 1
    上 table 吧。
    ferrum
        6
    ferrum  
       Apr 8, 2017   ❤️ 1
    这个就是最常见的办法了,兼容性也好。不用想其他的了。
    cheejay
        7
    cheejay  
    OP
       Apr 8, 2017 via Android   ❤️ 1
    @wukongkong @bdbai @est @ferrum
    感谢各位,我还是先这样用吧不折腾了……
    Sparetire
        8
    Sparetire  
       Apr 9, 2017
    我就奇怪只是文字居中,为什么就没有人用 text-align: center 的。。不要 display: inline-block ,只要 text-align: center 就好
    aaronlam
        9
    aaronlam  
       Apr 9, 2017
    @Sparetire 如果去掉了 display: inline-block 会不会背景就超出文字范围了?
    kfll
        10
    kfll  
       Apr 9, 2017 via Android   ❤️ 1
    @aaronlam p span hello world endspan endp
    p text-align center
    p span background blue
    IJustmaogepao
        11
    IJustmaogepao  
       Apr 10, 2017
    给你代码。。
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title></title>
    <style>
    div {
    text-align: center;
    }
    span {
    background-color: blue;
    }
    </style>
    </head>
    <body>
    <div>
    <span>asdf</span>
    </div>
    </body>
    </html>
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   988 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 22:18 · PVG 06:18 · LAX 15:18 · JFK 18:18
    ♥ Do have faith in what you're doing.