【问题标题】:Horizontal centering text over image via CSS通过 CSS 在图像上水平居中文本
【发布时间】:2012-03-01 20:36:44
【问题描述】:

考虑以下 html:

<div class="image">
    <img src="sample.png"/>
    <div class="text">
       Text of variable length
    </div>
</div>

地点:

.image {
    position:relative;
    text-align:center; // doesn't work as desired :(
}

.text {
    position:absolute;
    top:30px;
}

你能告诉我,是否有办法在.image div 的中心水平对齐文本?我不能使用left 属性,因为文本的长度未知,并且text-align 属性不适用于.text div :(

谢谢。

【问题讨论】:

    标签: css html image alignment


    【解决方案1】:

    试试下面的 CSS:

    .image {
        position:relative;
    }
    
    .text {
        left: 0;
        position:absolute;
        text-align:center;
        top: 30px;
        width: 100%
    }
    

    【讨论】:

    【解决方案2】:

    试试这个:

    .image {
        position:relative;
    }
    
    .text {
        position: absolute;
        top: 0;
        left: 0;
        width:100%;    
        height:100%;
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;
    }
    

    【讨论】:

    • 如果你使用 flex,为什么不直接使用 order 交换顺序而不是使用绝对定位技巧
    【解决方案3】:

    首先您需要浮动.image 元素,以便将其块级后代“折叠”到元素的宽度,然后在.text 元素上使用text-align

    .image {
        float: left;
    }
    .text {
        text-align: center;
    }
    

    JS Fiddle demo.

    或者您可以简单地给它一个display: inline-block,这将允许它包含其块级内容,并保留在文档流中:

    .image {
        display: inline-block;
    }
    .text {
        text-align: center;
    }
    

    JS Fiddle demo.

    【讨论】:

      【解决方案4】:

      你能不能使用 background-image: url('/yourUrl/'); 将图像用作'image' div 的背景图像然后不要将文本放在自己的 div 中,只需将其放在图像 div 中,然后应用 text-align: center;

      【讨论】:

        【解决方案5】:

        使用 Flex 是一种更“灵活”的选择 :-)

        #countdown {
          font-size: 100px;
          z-index: 10;
        }
        
        #countdown-div {
          width: 100vw;
          height: 100vh;
          display: flex;
          align-items: center;
          justify-content: center;
        }
        
        #bg-image {
          width: 100vw;
          height: 100vh;
          position: absolute;
          top: 0px;
          left: 0px;
        }
        
        <div>
          <div id="countdown-div">
            <h1 id="countdown">10</h1>
          </div>
          <img id="bg-image" src="https://lh3.googleusercontent.com/proxy/PKaxc9qp52MkavbkMnnbu0AZAGcqxJCoa7wIgtCmOr2e1x9ngdsteITX6x4JqDDFOhhdZmF79Ac5yevMGaUmcSaFnFYsHQtLPxHg56X_8PfP1fNkxMNXYd3EzhuCb3eJ2qQA">
        
        </div>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-06-21
          • 2013-07-23
          • 2017-03-26
          • 2018-09-23
          相关资源
          最近更新 更多