Search code examples
htmlcssposition

Absolute within position relative div?


Essentially I have two images a lamp with no light and one with a light and when the user hovers over the image it flicks the light on.

I'm trying to position the lamp to a specific location with position absolute which is fine but whenever I scale the page it changes position, now I know this is because it's out of the flow of the page so I read on related topics to put it within a div with position relative, I've done this but it still doesn't work.

#cont {
  position: relative;
  height: 100%;
}
#cont a {
  position: absolute;
  bottom: 69px;
  left: 350px;
}
.foo img:last-child {
  display: none
}
.foo:hover img:first-child {
  display: none
}
.foo:hover img:last-child {
  display: inline-block
}
<section class="flexheader">
  <img class="logo" alt="" src="image/logo.png">
  <img class="house" alt="" src="image/house.png">
  <div id="cont">
    <a class="foo" href="#">
      <img alt="" src="image/lampnolight.png">
      <img alt="" src="image/lamp.png">
    </a>
  </div>
</section>


Solution

  • You need to use this to make the scaling work perfectly:

    .flexheader,
    body, html {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    

    Snippet

    .flexheader,
    body, html {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    #cont {
      position: relative;
      height: 100%;
    }
    #cont a {
      position: absolute;
      bottom: 69px;
      left: 350px;
    }
    .foo img:last-child {
      display: none;
    }
    .foo:hover img:first-child {
      display: none;
    }
    .foo:hover img:last-child {
      display: inline-block;
    }
    <section class="flexheader">
      <img class="logo" alt="" src="//placehold.it/100?text=logo" />
      <img class="house" alt="" src="//placehold.it/100?text=house" />
      <div id="cont">
        <a class="foo" href="#">
          <img alt="" src="//placehold.it/100?text=lampnolight" />
          <img alt="" src="//placehold.it/100/ccf?text=lamp" />
        </a>
      </div>
    </section>