htmlcsscss-calc

Is there a pure CSS way to make a child element fit into parent with stepped (width) values


I have a container element that resizes dynamically. Inside the container I have another block element - let's say it is a h1 - by default and design that is the same width. I would like to make sure that the width of the h1 is always a multiple of e.g. 50px. (I would like to underline it with a repeating image of 50px width not showing a cut-off image also not stretching the image - otherwise a border-image could be the solution).

I tried something like --num: calc(100% / 50px) and a custom property rule to round the value and applying width: calc(var(--num) * 50px); , but that isn't working as the second value of a calc division must be a unitless number so the first step isn't working.

I could probably work around it with a lot of empty boxes inside an flex-container, and/or a lot of media queries but I'd rather not clutter my semantic structure (very much).

I can certainly solve it with JavaScript, and I probably will, but somehow I think I might just miss the right idea, as so much ist possible with pure css-magic in 2022.

I appreciate the input


Solution

  • CSS grid can do it:

    .wrapper {
      display: grid;
      grid-template-columns: repeat(auto-fill, 50px); /* your step */
      justify-content: center; /* remove if you want left align */
    }
    
    h1 {
      grid-column: 1/-1; /* take all the possible columns */
      
      /* to demoonstrate the repetition */
      padding-bottom: 80px;
      background: url(https://picsum.photos/id/1069/50/50) bottom left repeat-x;
    }
    <div class="wrapper">
      <h1>a title</h1>
    </div>