简体   繁体   English

图像高度和宽度被CSS覆盖

[英]Image height and width is overridden by css

<img src="img_forest.jpg" alt="Forest" width="600" height="400">

I have the above line in my html body tag. 我的html主体标签中有上述一行。 But the height and width specified here are overridden by the height and width specified for the img in the stylesheet. 但是,此处指定的高度和宽度被样式表中为img指定的高度和宽度所覆盖。

Why does this happen? 为什么会这样?

At this point your getting into more of styling the image element. 此时,您将更多地设计图像元素的样式 The width and height attributes initially tell the browser the necessary amount of space it needs to make on-screen for these images when the page loads. widthheight 属性最初告诉浏览器,当页面加载时,这些图像在屏幕上需要留出必要的空间量。

Tip: Always specify both the height and width attributes for images. 提示:始终同时指定图像的高度和宽度属性。 If height and width are set, the space required for the image is reserved when the page is loaded. 如果设置了高度和宽度,则在加载页面时保留图像所需的空间。 However, without these attributes, the browser does not know the size of the image, and cannot reserve the appropriate space to it. 但是,如果没有这些属性,浏览器将不知道图像的大小,并且无法为其保留适当的空间。 The effect will be that the page layout will change during loading (while the images load). 效果是页面布局将在加载过程中(图像加载时)改变。

http://www.w3schools.com/TAgs/att_img_width.asp http://www.w3schools.com/TAgs/att_img_width.asp

尝试使用内联样式来覆盖您的css文件,或在HTML页面中为您的图像的css选择器指定更多选项。

<img src="img_forest.jpg" alt="Forest" style='width:600px !important; height:400px !important;'>

That's because the width and height attributes set the intrinsic width and height of the image. 这是因为widthheight属性设置了图像的固有宽度和高度。

By default, width and height CSS properties have the value auto . 默认情况下, widthheight CSS属性的值是auto Since images are replaced elements, this means the intrinsic sizes will be used ( §10.3.2 and §10.6.2 ). 由于图像是替换的元素,因此这意味着将使用固有大小(第10.3.2节和第10.6.2节 )。

However, you can override that with some declaration, and then of course the image will be displayed with the specified size. 但是,您可以使用一些声明覆盖它,然后图像将以指定的大小显示。

If you don't want this, add important inline styles, which can't be overriden: 如果您不希望这样做,请添加重要的内嵌样式,这些样式不能被覆盖:

<img src="img_forest.jpg" alt="Forest" width="600" height="400"
     style="height: auto !important; width: auto !important" />

 img { height: 100px; width: 500px; } 
 <img src="/favicon.ico" alt="Forest" width="16" height="16" style="height: auto !important; width: auto !important" /> 

You can see width="600" is an attribute, but width:100px is a property. 您可以看到width="600"是一个属性,而width:100px是一个属性。 While rendering these attributes are converted to the respective style and placed at the beginning of the style sheet. 在渲染时,这些属性将转换为相应的样式,并放置在样式表的开头。

Check the accepted answer Click here . 检查接受的答案单击此处 This is what you want. 这就是你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM