skip to Main Content
.div1 {
  position: relative;
  padding-bottom: 25%;
  background: lightcoral;
}

.img-container {
  position: absolute;
  height: 100%;
  background: green;
}

.img1 {
  height: 100%;
  opacity: 50%;
}
<div class="div1">
  <div class="img-container">
    <img src="https://placehold.co/600x300" alt="" class="img1">
  </div>
</div>

Chrome result (expected result):

Screenshot of Chrome

Firefox result (wrong result):

Screenshot of Firefox

As you can see, in Firefox the width of the green div is just some random value, and not the width of its descendants (I fail to see any logic behind it).

Images must be able to have variable width, so this solution won’t work for me (can’t set fixed width on .img-container).

What am I doing wrong?

2

Answers


  1. Firefox is a little different when it comes to absolute positioning. Try to understand what actually absolute position works. The element having abs with height: 100% will cover fully if the parent container is also 100%

    you also have a padding-bottom i don’t understand why do you need padding bottom, this will make your children appear smaller.

    Try adding width: 100%; to img-container. i tinkered with your code in the inspector. it seemed to fix it. Try and let me know how it goes

    Login or Signup to reply.
  2. In Firefox, the width of the img container isn’t random. In fact it is the original width of the img (600px), CSS alone can’t determine the rendered width when the image’s height is based on a percentage.. What exactly do you want to achieve?
    if you really want to force it, use JS to determine the image width on page load.

    function changeWidth() {
      const container = document.querySelector('img-container');
      const img = document.querySelector('img1');
      container.style.width = img.clientWidth + 'px';
    }
    window.onload = changeWidth
    windw.onresize = changeWidth
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search