Horizontal centering text over image via CSS

前端 未结 5 660
长情又很酷
长情又很酷 2020-12-08 07:42

Consider the following html:

Text of variable length
相关标签:
5条回答
  • 2020-12-08 08:06

    First you need to float the .image element, in order to 'collapse' its block-level descendants to the width of the element, and then use text-align on the .text element:

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

    JS Fiddle demo.

    Or you could simply give it a display: inline-block, which will allow it to have its block-level contents contained, and remain in the document flow:

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

    JS Fiddle demo.

    0 讨论(0)
  • 2020-12-08 08:06

    Can you not use the image as the background image of the 'image' div using background-image: url('/yourUrl/'); and then rather than have your text in its own div simply place it in the image div and then apply text-align: center;

    0 讨论(0)
  • 2020-12-08 08:07

    Using Flex is a more"flexible" option :-)

    #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>
    
    0 讨论(0)
  • 2020-12-08 08:14

    Try this:

    .image {
    
        position:relative;
    }
    
    .text {
        width:100%;    
        height:100%;
        position: absolute;
        top: 0;
        left: 0px;
        justify-content: center;
        flex-direction: column;
        align-items: center;
        display: flex;
    }
    
    0 讨论(0)
  • 2020-12-08 08:19

    Try the following CSS:

    .image {
        position:relative;
    }
    
    .text {
        left: 0;
        position:absolute;
        text-align:center;
        top: 30px;
        width: 100%
    }
    
    0 讨论(0)
提交回复
热议问题