Jordan
Jordan

Reputation: 123

How to keep a div at the same spot on the background when resizing?

I am trying to keep a div at the same spot on a background. The problem is when I resize the window the div moves. Let me show you my issue with an example.

Here my markup.

html, body {
    margin: 0;
    padding: 0;
}

body {
    background: url("https://resize-elle.ladmedia.fr/rcrop/638,,forcex/img/var/plain_site/storage/images/beaute/maquillage/tendances/beaute-la-vraie-signification-des-emojis/le-smiley-qui-porte-des-lunettes-de-soleil/54410296-1-fre-FR/Le-smiley-qui-porte-des-lunettes-de-soleil.jpg") no-repeat fixed;
    background-size: cover;
    background-position-x: center;
}

.center {
    text-align: center;
    margin-top: 10rem;
}
<header>
  <div class="center">
    <h1>TITLE</h1>
  </div>
</header>

Try to adapt the margin-top value so that the title be just above the glasses. Now when you resize the window I would like the title to stay approximatively or exactly if possible above the glasses. And for some reasons I don't want background-position-y to be set to center. Is there a way to do so?

The issue is close to this one Divs always at the same spot of the background image? but it doesn't work.

Upvotes: 0

Views: 82

Answers (1)

tamarin
tamarin

Reputation: 549

I'm not sure there's a nice way to do that, but playing with media queries you can obtain an ok result.

html, body {
    margin: 0;
    padding: 0;
}

body {
    background: url("https://resize-elle.ladmedia.fr/rcrop/638,,forcex/img/var/plain_site/storage/images/beaute/maquillage/tendances/beaute-la-vraie-signification-des-emojis/le-smiley-qui-porte-des-lunettes-de-soleil/54410296-1-fre-FR/Le-smiley-qui-porte-des-lunettes-de-soleil.jpg") no-repeat fixed;
    background-size: cover;
    background-position-x: center;
}

.center {
    text-align: center;
    margin-top: 20vw;
}

@media only screen and (max-width: 638px){
  .center {
    text-align: center;
    margin-top: 20vh;
  }
}

@media only screen and (max-height: 450px){
  .center {
    text-align: center;
    margin-top: 20vw;
  }
}
<header>
  <div class="center">
    <h1>TITLE</h1>
  </div>
</header>

Upvotes: 1

Related Questions