0

I'm looking for a solution to this issue for an hour and what I found on internet never match exactly what I'm looking for. I want to center a text on a image with CSS. The height of the image is defined automatically in regard of the width of the div (which is a percentage).

Here the html code:

<div>
  <img src="image.jpg" id="image"/> 
  <span id="texte"> Texte </span>
</div>

Here the CSS code (which doesn't work):

#div
{
  position: relative;
  margin: 0px;
  padding: 0px;
  width:45%;
  text-align:center;
}

#texte
{
  display: block;
  padding: 0px;
  margin-left:auto;
  margin-right:auto;
  z-index: 2;
}

#image
{
  width:100%;
  height:auto;
  display: block;
  padding: 0px;
  z-index: 1; 
}

Thanks for your help.

tienow
  • 171
  • 12
  • This may help you: http://stackoverflow.com/questions/8708945/how-to-position-text-over-an-image-in-css. Look at the first answer. span is for something within an element that you want different from another inside the same element. ie:

    Green textblue text span>green text

    . Your text needs the p tag. Also, div is not an id on its own. You need to specify
    – CHoltzman Aug 31 '15 at 04:37

2 Answers2

0

If you remove the # from the div in the CSS (since it's a tag, not an ID), and add the following properties to your #text block:

position: absolute; /* so that the "top" property can be applied */
top: 50%; /* puts the top of the element halfway down what it's relative to, in this case the div */
margin-top: -.6em; /* assuming no wrapping, this slight adjustment makes it so the middle of the text (instead of its top) runs roughly through the middle of the parent */
width: 100%; /* in case you meant horizontal centering instead. this allows the parent's "text-align: center" to be applied */

I think that should accomplish what you're looking for. If the text is longer than one line and you need exact vertical centering, I think you'd have to use a JavaScript solution. Here's a JS Fiddle that has your CSS with my edits (though some of your CSS may no longer be necessary now).

Max Starkenburg
  • 1,499
  • 1
  • 15
  • 21
0

Try this

* {
  box-sizing: border-box;
  font-family: sans-serif;
}

.container {
   position: relative;
   overflow: hidden;
}

img {
   width: 100%;
   opacity: .8;
} 

.centered-text {
   display: inline-block;
   position: absolute;
   top: 50%;
   left: 50%;
   color: white;
   padding: .7em 1em;
   text-align: center;
   font-size: 1.5em;
   background-color: rgba(0, 0, 0, .4);
   -webkit-transform: translate(-50%, -50%);
   -moz-transform: translate(-50%, -50%);
   -o-transform: translate(-50%, -50%);
   -ms-transform: translate(-50%, -50%);
   transform: translate(-50%, -50%);
}
<div class="container">
  <img src="https://parrot-tutorial.com/images/nature_autumn.jpg">
  <span class="centered-text">Text</span>
</div>

Reference:How To Position Text Over an Image

Vishal
  • 268
  • 4
  • 3