css - CSS:防止
问题描述
我试图阻止图像延伸到高度设置为 0 且 padding-top 为 100% 以保持 1:1 纵横比的网格项的边界之外。使用<img>
元素(左侧)时效果很好,但不使用<picture>
元素(右侧)。
.grid {
display: grid;
grid-template-columns: 1fr 1fr
}
.item {
display: block;
position: relative;
padding-top: 100%;
height: 0;
background-color: grey;
border: 1px solid black;
}
.inner {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: grid;
grid-template-rows: minmax(20px, 1fr) auto auto minmax(20px, 1fr);
}
.text {
grid-row-start: 2;
text-align: center;
margin-top: 0;
margin-bottom: 15px;
}
.img {
grid-row-start: 3;
max-height: 100%;
width: auto;
max-width: 100%;
display: block;
margin-left: auto;
margin-right: auto;
}
<ul class="grid">
<li class="item">
<div class="inner">
<p class="text">Text</p>
<img class="img" src="https://images.unsplash.com/photo-1621250755294-57cf625b4a9a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80" />
</div>
</li>
<li class="item">
<div class="inner">
<p class="text">Text</p>
<picture class="img">
<source srcset="https://images.unsplash.com/photo-1621250755294-57cf625b4a9a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80 1x, https://images.unsplash.com/photo-1618236507249-9960f2c6a53d?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80 2x"
media="(min-width: 360px)">
<img src="https://images.unsplash.com/photo-1621250755294-57cf625b4a9a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80" />
</picture>
</div>
</li>
</ul>
解决方案
也给 img 放一个类。
<img src="https://images.unsplash.com/photo-1621250755294-57cf625b4a9a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80" />
至
<img class="img" src="https://images.unsplash.com/photo-1621250755294-57cf625b4a9a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80" />
将溢出:自动添加到类img
推荐阅读
- android - Flutter:只有在登录成功后按下返回按钮时才会出现主屏幕
- elasticsearch - Bulk API 中 ES 中的 ES 日志摄取是否有限制?
- kubernetes - 显示关闭 pod 的 GKE GUI 概览
- java - Java 中的 java Files.lines 和 Files.newBufferedReader().lines 之间的实际区别是什么?
- django - 如何使用 Django Cassandra 引擎连接 AWS Keyspace?
- javascript - 阻止打开文件选择器对话框 - Selenium GeckoDriver
- .net-core - CLR 编译器
- css - 移动设备正在显示桌面内容布局的“缩影”,而不是根据其宽度进行相应调整
- c++ - 使用按钮 c++ winapi
- vim - 表格vim中左侧第一个单词右对齐