toytu
toytu

Reputation: 13

How to avoid text from moving away from image when resizing the browser?

I have been trying to keep the text inside the image when I resize the browser. I've tried floating it as well.

<div class="image">
<img src="background2.jpg">
<h1>Hello</h1>
</div>

And here is the CSS

.image img{
    width: 90%;
    display: block;
    margin: auto;
    position: relative;
}
h1{
    position: absolute;
    top: 50%; 
    left: 50%; 
    width: 100%;
}

Upvotes: 0

Views: 1202

Answers (2)

Michael Coker
Michael Coker

Reputation: 53709

You want the parent element (.image) to be position: relative so that it's what the h1 will be absolutely positioned relative to. You can also give it the width and margin that center it at 90% of the page. Then make the image 100% width of the parent, and use top: 50%; left: 50%; transform: translate(-50%,-50%); to absolutely center the text vertically and horizontally.

.image {
  width: 90%;
  display: block;
  margin: auto;
  position: relative;
}

.image img {
  width: 100%;
  display: block;
}

.stuff {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  margin: 0;
}
<div class="image">
  <img src="http://kenwheeler.github.io/slick/img/fonz1.png">
  <div class="stuff">
    <h1>Hello</h1>
    <h2>Foobar</h2>
  </div>
</div>

Upvotes: 3

Peter Cadwell
Peter Cadwell

Reputation: 109

You can try making the image the background of the parent div:

<div class="image">
  <h1>Hello</h1>
</div>

The css would look something like this:

.image {
  background: url('background2.jpg') no-repeat center center;
  background-size: cover;
}

Upvotes: 0

Related Questions