如何确保高度不超过父的高度,同时还要维护图像的纵横比

发布于 2025-02-04 07:17:56 字数 125 浏览 4 评论 0原文

我有一个宽度应尽可能大的图像,我希望不超过父母的高度,同时还保持纵横比的高度为16:9。目前的问题是,它可以很好地工作,直到屏幕尺寸为1591px,如果大于该屏幕大小,高度就超过了,并且出现了垂直滚动条。我不想要那种行为。我该如何实现?

I have an image which width should be as large as possible and I want it's height to not exceed the height of the parent while also maintaining the aspect ratio of 16:9. The issue right now is, it works well till the screen size is 1591px, if it gets bigger than that, the height exceeds and the vertical scroll bar appears. I don't want that behavior. How can I achieve that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

清音悠歌 2025-02-11 07:17:56

Update :从一个问题中假定的原始答案是图像是HTML IMG。解决方案是将宽度设置为[其容器的100%],并将高度设置为70VH,并使用对象拟合。

但是,这不是IMG,而是画布。

已知所需的纵横比为16/9。因此,该段将最大宽度设置为100%(任何是容器的)和最大高点为70VH。

这样,永远不会有任何溢出,画布将在这些约束中尽可能大。

body {
  width: 100vw;
  margin: 0;
}

canvas {
  max-width: 100%;
  max-height: 70vh;
  aspect-ratio: 16 / 9;
  background: green;
}
<canvas width="1600" height="900"></canvas>

UPDATE: the original answer assumed from the question that the image was an HTML img. The solution was to set width to 100% [of its container] and height to 70vh and use object-fit.

However, it is not an img it is a canvas.

The required aspect ratio is known to be 16 / 9. This snippet therefore sets the max-width to 100% (of whatever is the container) and the max-height to 70vh.

This way there can never be any overflow and the canvas will be as big as it can be within those constraints.

body {
  width: 100vw;
  margin: 0;
}

canvas {
  max-width: 100%;
  max-height: 70vh;
  aspect-ratio: 16 / 9;
  background: green;
}
<canvas width="1600" height="900"></canvas>

小忆控 2025-02-11 07:17:56

由于溢出而出现滚动条,您可以

  1. 使用“溢出:隐藏;”使用
body{
    overflow: hidden;
}
  1. 2件事。您可以使用最大宽度来确定元素的最大宽度,并将其设置在

我希望它有用的两个元素上

the scrollBar appears because of the overflow you can do 2 things

  1. use the "overflow: hidden;"
body{
    overflow: hidden;
}
  1. you can use max-width to determine the max-width of the element and set it on both of the elements

I hope it was helpful ????

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文