Home > Net >  How to center text over an image
How to center text over an image

Time:01-29

I'm trying to center both horizontally and vertically a text block above an image. I've reviewed other posts but they don't seem to resolve my problem.

Here's the code:

<body>
   <div id="top-of-page">
     <img src="images/etudes.png">
     <div id="text-block">
       <h1>Title</h1>
     </div>
   </div>

#haut-de-page {
  position: relative;
  margin: 10px;
}

#top-of-page img {
  width: 100%;
}

#text-block {
  position: absolute;
  top: 5px;
  margin: 0 auto;
  background-color: rgba(0, 0, 0, .5);
  color: white;
  padding-top: 20px;
  padding-left: 20px;
}

Even though I've set the div "text-block" position:absolute the text keeps appearing under the image.

Do you have ideas ?

CodePudding user response:

From what I understood from your question, you want to center your text both vertically and horizontally on top of your image. Just use margin-left for horizontal centering and margin-top for vertical one.

#haut-de-page {
    position: relative;
    margin: 10px;
}

#top-of-page img {
    width: 100%;
}

#text-block {
    position: absolute;
    top: 5px;
    margin-left: 689px; /* This will center it horizontally */
    margin-top: 489px; /* This will center it vertically */
    background-color: rgba(0, 0, 0, .5);
    color: white;
    padding-top: 20px;
    padding-left: 20px;
    text-align: center;
}

That will center your text both vertically and horizontally on top of the image.

CodePudding user response:

Try This:

HTML:

<div id="top-of-page">
    <div >

        <img src="images/etudes.png">
        <div id="text-block">
            <h1>Title</h1>
          </div>

    </div>
  </div>

CSS:

.image{

position: relative;

}

#text-block{

position: absolute;
top: 50%;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%);
justify-content: center;
align-items: center;
z-index: 100;
margin: 0 auto;
background-color: rgba(0, 0, 0, .5);
color: white;

}

  • Related