reZach
reZach

Reputation: 9429

CSS Horizontally align text over image

I don't know if it is possible, but is it possible for a <span> of variable text length to be horizontally aligned over an image? The one catch with this, is I'd like the <span> to have a background color and the background color block should overlap the image.

I've tried setting the <span> to display:inline-block but it doesn't seem to end up horizontally aligned. Here is the code if you don't want to look in the fiddle (the HTML here should remain the same if-at-all-possible)

The Code (https://jsfiddle.net/6c9gmvom/1/):

#wrapper {
  width:100%;
}
.txt {
  text-align:center;
  margin:0 auto;
  width:40px; /* ideally I would not want to use a fixed width here */
  background-color:#ffffff;
} 
img {
  height:30px;
  width:100%;
}
<div id="wrapper">
  <img src="http://seedmagazine.com/slideshow/the_long_shot/img/8_the_long_shot_ss.jpg">
  <div id="modulewrapper">
    <span class="txt">hey</span>
    <div id="module"></div>
  </div>
</div>

Upvotes: 1

Views: 72

Answers (4)

Scott
Scott

Reputation: 21882

You can set the image as a background image... then set the span to display block.....

#wrapper {
  width:100%;
}
.txt {
  text-align:center;
  margin: 10px auto;
  background-color:#ffffff;
  display: block;
  text-align: center;
} /* ideally I would not want to use a fixed width here */
img {
  height:30px;
  width:100%;
}

#modulewrapper { 
  padding: 200px 0;
background: url(http://seedmagazine.com/slideshow/the_long_shot/img/8_the_long_shot_ss.jpg) no-repeat center center; }
<div id="wrapper">
  <div id="modulewrapper">
    <span class="txt">hey</span>
    <div id="module"></div>
  </div>
</div>

Upvotes: 1

Mr. Sven
Mr. Sven

Reputation: 78

.txt {
  text-align:center;
  margin:0 auto;
  width:100%;
  background-color:#ffffff;
  position: fixed;
  left: 0;
  top: 15px;
}
img {
  height:30px;
  width:100%;
  position: relatable;
}

Upvotes: 0

Juan
Juan

Reputation: 80

I'm not too sure I understand what it is you are asking. If im not mistaken what you want is for the text to be on top of the image. This can be done as seen https://jsfiddle.net/6c9gmvom/9/

 #wrapper {width:100%;position:relative}
.txt {
  position:absolute;
  text-align:center;
  margin:0 auto;
  width:40px;
  background-color:#ffffff; 
  z-index: 100;
  width:100%;
}
img {
height:30px;width:100%;
}

.imageClass{
  position:absolute;
   left: 0;
  top: 0;
}

Upvotes: 0

xxxmatko
xxxmatko

Reputation: 4142

You can align it with css. I've updated your fiddle, check it out to see the result https://jsfiddle.net/6c9gmvom/8/

The css I've added is:

#wrapper {
  width:100%;
  position: relative;
}
#modulewrapper {
  text-align:center;
  position: absolute;
  top:0;
  left:0;
  right:0;
}

Upvotes: 1

Related Questions