Search code examples
htmlcsspositionwidthabsolute

how to inherit the width for the for the child of a child


I have 3 tags: first main div, second is a figure and inside there is a figcaption, like this:

<div class="main-div">
  <figure>
    <figcation>
    </figcaption>
  </figure>
</div>

I assigned the main div to be 80% of the width of the whole document. Then I've set the figure to be 100% of its parent, so it completely wraps around the main div.

After that I gave the figcation a position of absolute and I want it to have 100% of the width of the main div like the figure, because its width just runs as the content inside ends.

So how to assign the width for figcaption to be the full width of the main div?

I tried inheriting but it doesn't work. Also I can't get the figcaption tag outside of the figure because semantically, that would be wrong.


Solution

  • I think you're missing position: relative on one of the figcaption's parent elements div or figure:

    figure {
        position: relative;
    }
    
    figcaption {
        position: absolute;
    }
    

    If you use position: absolute; the top|right|bottom|left values as well as width and height values like percentages are calculated in relation to the closest parent that doesn't have position static. So it's relative to the closest element with position relative|absolute|fixed or at last the html-element.

    Demo

    Try before buy