适合父级并保持纵横比的 Div [英] Div that fits into parent and maintains an aspect ratio

查看:48
本文介绍了适合父级并保持纵横比的 Div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个保持纵横比的 div 元素:它根据宽度计算高度(使用填充技巧).我想要做的是将这个 div 放入另一个通过适应最大可用空间,垂直和水平,不裁剪.我认为最接近我想要的是 object-fit: contains - 仅 img.

我希望 div 在保持纵横比的同时覆盖可能的最大高度和宽度.没有垂直或水平裁剪.

仅使用 CSS 是否可行?如果是这样,如何?

更新:一篇不错的

解决方案

好吧,看来单靠 CSS 解决不了.如果有人感兴趣,我已经整理了一个 React 组件 来完成这项工作(测试和更好的自述文件,当我有时间的时候).

它将其子元素包装到一个 div 中,并使用 JavaScript 计算该 div 的宽度和高度,以便在保持给定纵横比的同时容纳可用空间.它基本上会拉伸包装纸,直到其中一侧达到最大值.

重大更新已找到仅 CSS 的解决方案

I've got a div element that maintains an aspect ratio: it calculates its height based on its width (using the padding trick). What I'd like to do is to put this div into another one by fitting the maximum space available, vertically and horizontally, no crop. I think the closest thing to what I want is the object-fit: contain - which is img only.

I want the div to cover the max height and width possible while maintaining the aspect ratio. No vertical or horizontal crop.

Is it even possible with CSS only? If so, how?

Update: A good article where things are at the moment.

code (Can be any other solution, doesn't have to be built on this snippet):

html,
body {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}

.container {
  position: relative;
  width: 100%;
}

.container:before {
  content: "";
  display: block;
  width: 50%;
  padding-top: 50%;
}

.embed {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: red;
}

<div class="container">
  <div class="embed">
    this should accommodate all the available space and maintain aspect ratio, no crop when width is too wide
  </div>
</div>

解决方案

Ok, it looks like it can't be solved by CSS only. If anyone interested, I've put together a React component that does the job (Tests and better README soon, when I have time).

It wraps its children into a div and uses JavaScript to compute the width and height of that div in order to accommodate the available space while maintains the given aspect ratio. It basically stretches the wrapper until one of the sides reaches its maximum.

BREAKING UPDATE a CSS only solution has been found!

这篇关于适合父级并保持纵横比的 Div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆