【问题标题】:CSS Square based on parent height基于父高度的 CSS Square
【发布时间】:2020-01-18 23:02:33
【问题描述】:

我目前正在开发一个网站,我希望图像是其父级高度的 25%。

我查看了关于 SO 的以下答案以及其他网站上的一些其他类似答案:

上述答案的问题是它要么使用视口单位(vh),要么是基于宽度的纵横比。就我而言,我想将一个元素设置为其父高度的 25%。我试过下面的代码,但它只是将它的宽度设置为 100%。

main {
    --main-height: calc(100vh - var(--nav-height) - var(--body-top-padding)); 
    min-height: var(--main-height);
}

section {
    border: 1px solid red;
    width: 100%;
    min-height: calc(var(--main-height) / 2);
}
#profile > img {
    border: 1px solid black;
    height: 25%;
    padding-left: 100%;
}

这里,#profile 是一个 ID 为 profile 的部分。

编辑

这就是我想要做的事情:

#profile > img {
    border: 1px solid black;
    --width: calc(0.25 * var(--main-height));
    min-height: var(--width);
    width: var(--width);
}

有没有更好的方法不使用 CSS 属性和计算?

【问题讨论】:

  • 您可以发布您案例的完整代码吗? #profile 的风格是什么?
  • @Nitheesh 更新了信息。

标签: html css aspect-ratio


【解决方案1】:

根据给定的细节,这应该足够了:

.parent {
  height: 300px;
  width: 300px;
  border: 1px solid black;
}

.parent img {
  height: 25%;
  width: auto;
}
<div class="parent">
  <img src="https://visualhunt.com/photos/2/cat-feline-cute-domestic-young-looking-curious.jpg?s=s" />
</div>

不过,我应该提到一些 CSS 限制:

  • CSS 相对高度和宽度 (%) 只能取自确定值。这意味着只有当父级具有相对高度时,才能将子级设置为相对高度,宽度也是如此。
  • 不建议调整图像大小,因此设置其中一个属性并让另一个automatically 修复它的比例就足够了。

查看它的一种简单方法是获取此 sn-p 并将父级的高度值更改为不同的值,然后查看图像如何受到影响。

如果父级的高度不能通过 CSS 确定,您可以使用 DOM “破解”此功能。

setTimeout(() => {
  let parent = document.getElementById('parent');
  let image = document.querySelector('#parent img');
  
  let parentHeight = parent.offsetHeight;
  image.style.height = (parentHeight / 4) + 'px';
}, 2000);
#parent {
  height: 50%;
  width: 50%;
}

#parent img {
  height: 25%;
  width: auto;
}
<div id="parent">
  <img src="https://visualhunt.com/photos/2/cat-feline-cute-domestic-young-looking-curious.jpg?s=s" />
</div>

我不会称其为完美示例,因为老实说,在此 sn-p 功能中模拟未知高度的容器很困难 - 但我将其延迟 2 秒以使示例可视化。

【讨论】:

  • 感谢您的回答!不幸的是,我不知道父母的大小。
  • 如果父级的高度不确定,您将不得不求助于 Javascript。我会将其添加到我的答案中。
  • 感谢您推荐 JavaScript 方法。如果可能的话,我希望有一种优雅的 CSS 方式来做这件事。我在编辑中想出了一个,但它看起来还是有点像 hack。
  • 嗯,你试过基本的height: 25%; width: auto吗?也许简单的解决方案一直都是正确的解决方案
  • 不幸的是,如果我 width: auto,它会创建一个正方形,但高度为 100%。还是谢谢!
猜你喜欢
  • 2014-01-09
  • 1970-01-01
  • 2018-08-27
  • 2019-07-19
  • 1970-01-01
  • 2016-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多