在< img>上设置宽度时,无论是宽度还是最大宽度,我都看到许多开发人员和一些框架(如bootstrap)也设置了height:auto. 高度:在这种情况下需要自动,如果是这样,为什么? (假
... . . 在< img>上设置宽度时,无论是宽度还是最大宽度,我都看到许多开发人员和一些框架(如bootstrap)也设置了height:auto.
高度:在这种情况下需要自动,如果是这样,为什么? (假设您希望在调整大小时保持图像成比例,并且之前未在CSS中设置该高度.)
有人提到Windows Phone 8上的IE10需要它.(这对我来说似乎很奇怪.)可能有些浏览器需要这个设置吗?
示例(fiddle):
div{ border: 2px solid red; width: 300px;}.maxwidth{ max-width: 100%;}.width{ width: 100%;}
<p><code>max-width: 100%</code>:</p><div><img class="maxwidth" src="https://placeimg.com/640/480/animals"></div><p><code>width: 100%</code>:</p><div><img class="width" src="https://placeimg.com/640/480/animals"></div><p>No <code>height: auto</code> is used,but images still stay proportional.</p>.
解决方法
. 对于初学者来说,initial value forheight
is auto
,所以除非在其他地方被覆盖,否则你不需要指定身高:自动.
此外,我不知道这与img元素本身在CSS图像(背景等)上有多紧密关系,但我相信浏览器无论如何都应该自动处理.如果这个文档也适用于img元素,我相信CSS Image Values and Replaced Content Module Level 3的Default Sizing Algorithm部分解释了浏览器应该如何处理:
.
The default sizing algorithm is defined as follows:
-
If the specified size is a definite width and height,the concrete object size is given that width and height.
-
If the specified size is only a width or height (but not both) then the concrete object size is given that specified width or height. The other dimension is calculated as follows:
-
If the object has an intrinsic aspect ratio,the missing dimension of the concrete object size is calculated using the intrinsic aspect ratio and the present dimension.
-
Otherwise,if the missing dimension is present in the object’s intrinsic dimensions,the missing dimension is taken from the object’s intrinsic dimensions.
-
Otherwise,the missing dimension of the concrete object size is taken from the default object size.
-
更新
似乎Bootstrap使用它来覆盖img元素上存在的任何自定义高度属性,以确保始终根据宽度计算高度.
. . .. ...