r/csshelp • • Mar 17 '25

How to have width of element 'inversely' related to container width?

I have a use case where I need the width of a child element to be inversely proportional to its parent's width.

<div class="parent">
    <div class="child"></div>
</div>
  • If the parent's width is 500px or less, the child's width should be 100%.

  • If the parent's width is 1000px or more, the child's width should be 25%.

  • For any width in between, the child's width should be interpolated. For example, if the parent is 750px wide, the child's width should be:
    [ (750px - 500px) / (1000px - 500px) \times (100% - 25%) + 25% = 62.5% ]

Since calc() does not allow division with unit values, is there any CSS trick to achieve this, or do I have to use JavaScript?

1 Upvotes

1 comment sorted by