user1283776 user1283776 - 14 days ago 8
Sass (Sass) Question

Overlay text over centered image?

I want to overlay text over a centered image. The following approach feels very hacky but works when the window has fixed size:

$Illustrationwidth: 509px;

.Illustration {
position: relative;
text-align: center;
margin-top: 60px;

&_tricky {
position: absolute;
text-align: left;
top: 24px;
left: 290px;
width: 300px;
}

&_answered {
position: absolute;
text-align: left;
top: 73px;
left: 290px;
width: 300px;
}

&_attention {
position: absolute;
text-align: left;
top: -30px;
left: 96px;
}
}


Here is the HTML I am using:

<div class="IntroIllustration">
<img src="images/illustration.png"/>

<h2 class="Illustration_attention">header above the image</h2>
<div class="Illustration_tricky">an overlayed text</div>
<div class="Illustration_answered">another overlayed text</div>
</div>


However, it does not work if the user changes the width of the window.

How can I make this work even when the window can change width? The solution needs to work for IE 10+ and for the latest two versions of Chrome.

Also, please educate me and help me become better at CSS :-)

Answer

UPDATE: I see your code now. I added some background color and font-sizes as extras so you can get a better idea of what it is doing.

Use % and for font-size vw instead of px and it will all shrink responsively.

#Illustration {
  position: relative;
  max-width: 509px;
  margin: 0 auto;
}
.Illustration_attention {
  font-size: 4vw;
  font-family: 'Roboto Slab', Rockwell, Serif;
  font-weight: bold;
  color: #000;
  text-align: center;
}
.Illustration_tricky {
  position: absolute;
  background: green;
  text-align: center;
  margin-top: 10%;
  left: 10%;
  font-size: 3vw;
}
.Illustration_answered {
  position: absolute;
  background: white;
  text-align: center;
  margin-top: 30%;
  left: 20%;
  font-size: 2vw;
}
.Illustration img {
  display: block;
  position: absolute;
  width: 100%;
  height: auto;
}

DEMO

Comments