css - 如何在保持标签纵横比的DIV中插入图像?
问题描述
我做了这个代码:
<div id="divImage" style="background-color: skyblue;height: 200px;">
<div style="background-color: red;width: 8%;height: 60px;margin-left: 20px; position: relative;top:50%;margin-right: auto;transform: translateY(-50%);"></div>
<div style="background-color: red;width: 8%;height: 60px;margin-right: 20px; position: relative;top:50%;margin-left: auto;transform: translateY(-150%);"></div>
</div>
divImage
我需要在宽度为 100%的图像中插入图像。为此,divImage
高度必须不固定(height: 200px;
)。我的目的是让它divImage
适应任何屏幕尺寸(以% 为单位)。
解决方案
您可以使用其伪元素强制您的盒子保持纵横比。这里的前元素总是有一个特定的填充顶部,这使得盒子占据了相对于其宽度的高度,因为100%
等式中的总是指容器的宽度。
.divImage {
&:before {
// Change this line to adjust the aspect ratio
// 1px / 1px will for example give you a square box.
// The first value refers to the height-part
padding-top: 5px / 10px * 100%;
content: "";
width: 1px;
margin-left: -1px;
float: left;
height: 0;
}
&:after { /* to clear float */
content: "";
display: table;
clear: both;
}
}
如果您想在覆盖框的 div 中使用图像,请添加以下内容:
.divImage {
position: relative;
img {
position:absolute;
width: 100%;//might not be necessary, just check if it works without
height: 100%;//might not be necessary, just check if it works without
object-fit:cover; //or contain if you dont want it to fill the container
}
}
推荐阅读
- html - 在 React Web 应用程序中单击文本框或文本区域时键盘消失
- wildfly - Wildfly 挂起导致 undertow websocket 连接失败
- nuxt.js - Nuxt 无法在页面组件中实现 head 功能
- post - AttributeError: 'set' 对象在调用 POST 时没有属性 'items'
- r - 我已经使用 openxlsx 从 R 输出数据,并希望在部分标题字符串中添加上标
- sql-server - Maps API 正在运行,但突然停止。计划为 ERP 创建 SP
- python - ROCAUC 图例和 x/y 轴字体大小使用 Yellowbrick
- reactjs - 将用户 IP 地址存储在数据库中,以便以后进行比较
- json - 在 Postgresql 10.8 中,如何将 char 类型字段更改为 json 类型,然后获取 json 字符串中的数字?
- node.js - 当我从 MongoDB 传递视频时,为什么我的视频无法播放?