我正在尝试根据属性 (width=XX)
而不是 CSS 设置图像大小。这就是当您使用 UI 拖动 Angular 将图像调整为 85 x 30 时 Wordpress Html 编辑器设置的内容。但是,主题有一些 css height/width:auto
这使得 img
转到它的自然尺寸,我找不到“杀死”该 CSS 的方法,因此它恢复为内联尺寸。 (当然没有编辑主题 CSS)
我尝试使用 width:unset
和 inherit
无济于事。有任何想法吗?
/* Untouchable CSS */
.row .col img:not([srcset]) {
width: auto;
}
.row .col img {
height: auto;
}
/*End Untouchable CSS */
img{
width:unset !important; /*doesn't work*/
height:unset !important; /*doesn't work*/
}
<div class="row">
<div class="col">
<a href="#"><img width="85" height="30" src="https://placehold.it/340x120/00aaaa/fff/?text=Logo"></a>
</div>
</div>
最佳答案
只需将属性 srcset=""
添加到图像即可避免应用第一个样式并删除您添加的样式。这个想法是只将一个 CSS 属性保留为 auto
(高度或宽度),另一个将获得图像上指定的值,并且您的图像将具有所需的高度/宽度:
顺便说一句,我建议您为 srcset
指定一个正确的值并且不要将其留空
/* Untouchable CSS */
.row .col img:not([srcset]) {
width: auto;
}
.row .col img {
height: auto;
}
/*End Untouchable CSS */
<div class="row">
<div class="col">
<a href="#"><img width="85" height="30" srcset="" src="https://placehold.it/340x120/00aaaa/fff/?text=Logo"></a>
</div>
</div>
更新
要添加更多说明,指定 width:auto
和 height:auto
会覆盖图像属性中指定的值。
auto
值意味着浏览器将为指定元素计算并选择宽度。然后图像将获得其原始/默认大小。
通过删除 auto
值之一(在本例中为宽度),将再次考虑图像属性的值,而另一个值,因为它始终是自动的,将通过以下方式计算浏览器,在这种情况下,它将适合属性中的值,因为浏览器将在计算时保持比率,但您可以指定任何您希望不考虑的值。
下面是一段代码来展示这一点:
.col img {
height: auto;
}
.col2 img {
height: 100px;
}
.col3 img {
height: 300px; /* 300px will overribe the value in the attribute */
width:auto; /* auto will override the attribute so the browser will calculate the width by keeping the ratio of the image*/
}
<div class="col">
<img width="85" height="30" srcset="" src="https://placehold.it/340x120/00aaaa/fff/?text=Logo">
</div>
<div class="col">
<!-- specify a big height value here -->
<img width="85" height="300000" srcset="" src="https://placehold.it/340x120/00aaaa/fff/?text=Logo">
</div>
<div class="col2">
<!-- for this one the width is specified in attribute and height in CSS -->
<img width="85" height="300000" srcset="" src="https://placehold.it/340x120/00aaaa/fff/?text=Logo">
</div>
<div class="col3">
<img width="85" height="300000" srcset="" src="https://placehold.it/340x120/00aaaa/fff/?text=Logo">
</div>
这是一个有更多细节的类似问题:
关于css - 取消设置宽度以恢复为内联 html 属性 "width=XX",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47852934/