是否有一种纯粹的 CSS 方法可以使子元素适合具有阶梯(宽度)值的父元素

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

我有一个动态调整大小的容器元素。在容器内,我有另一个块元素 - 假设它是一个 h1 - 默认情况下和设计具有相同的宽度。 我想确保 h1 的宽度始终是例如的倍数50 像素。 (我想用 50px 宽度的重复图像强调它,不显示截止图像也不拉伸图像 - 否则边框图像可能是解决方案)。

我尝试了 --num: calc(100% / 50px) 和自定义 属性 规则来舍入值并应用宽度:calc(var(--num) * 50px); ,但这不能作为计算的第二个值除法必须是无单位的数字,因此第一步无效。

我可能可以在 flex-container 中使用很多空框来解决它,and/or 很多媒体查询,但我不想弄乱我的语义结构(非常多)。

我当然可以用 JavaScript 解决它,我可能会,但不知何故,我认为我可能只是错过了正确的想法,因为在 2022 年使用纯 css-magic 可能会有这么多.

感谢您的投入

CSS网格可以做到:

.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>