简体   繁体   中英

Horizontal centering text over image via CSS

Consider the following html:

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

Try the following CSS:

.image {
    position:relative;
}

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

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;
}

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 .

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;

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>
.banner-wrap {
   height:auto;
   margin: auto;
   text-align:center;
   position: relative;
   margin-bottom: 3rem;
}

.banner-pic {
   width: 100%;
}

.text_over_image {
   position: absolute;
   margin: auto;
   top: 0;
   left:0;
   right:0;
   bottom:0;
   color:#fff;
   height:100px;
   width: 100%;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM