javascript - 如何以纵横比显示图像?
问题描述
我正在使用 css 网格。我想使用纵横比显示我的图像。取决于宽度我想显示图像。我不想给出高度的硬线值。是否可以在不给出高度的情况下显示图像。换句话说,我取决于宽度我想显示图像而不给出任何值高度 。
这是我的代码
https://codesandbox.io/s/condescending-flower-m616l?file=/index.html
.abc {
display: grid;
grid-template-columns: repeat(12, 6.697%);
grid-template-rows: 18px repeat(4, 1fr);
border: 1px solid green;
height: 320px;
}
.one {
grid-column: 2/5;
grid-row: 3/5;
border: 1px solid;
}
.two {
grid-row: 1/5;
grid-column: 2/5;
border: 1px solid #ee0;
}
.two div {
max-width: 100%;
/* height: 100%; */
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Static Template</title>
</head>
<body>
<div class="abc">
<div class="one">
<p>
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Voluptates
culpa iste facaudantium Lorem ipsum,
</p>
</div>
<div class="two">
<div style="background-image: url('hero.png');"></div>
</div>
</div>
</body>
</html>
我 /* height: 100%; */
只给我的图像显示?
解决方案
使用 CSSaspect-ratio
属性为图像的 div 设置纵横比。
.two div {
aspect-ratio: 1 / 1;
background-size: cover;
}
尽管在撰写本文时aspect-ratio
尚未得到所有主要浏览器的支持。caniuse.com - 纵横比。
作为后备,使用带有伪元素的填充技巧。
@supports not (aspect-ratio: 1 / 1) {
.two {
position: relative;
}
.two::before {
content: "";
display: block;
padding-top: 100%; /* This will give it the same height as width. */
}
.two div {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
}
推荐阅读
- angular - 将请求限制为 Angular
- sql - 在联合错误语法错误上使用组更新
- ios - 显示以编程方式创建的 UITextView / UITextField 的剪切/复制/粘贴菜单
- python - 绘图模型不显示模型层,仅显示模型名称
- mysql - 将 MySQL 配置为数据库后端后 - 表项目仍然为空
- swift - 当值具有关联类型时扩展字典
- pandas - Pandas:一种更有效的方法来检查列开始并分配新列?
- build - Azure DevOps Pipeline Build 无法在 GAC 中缺少 DLL 引用
- python - 如何在循环中使用熊猫将行添加到数据框中?
- reactjs - react如何处理props的变化?