HTML:如何使用 CSS 作为链接样式表添加图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21412536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML: How to add an image using CSS as linked style sheet
提问by user3245569
Here's my code. I'm trying to add an image called lg.png into the HTML and be able to edit the length/width in the css file. The lg.png is located in the same folder as the index.html and styles.css
这是我的代码。我正在尝试将一个名为 lg.png 的图像添加到 HTML 中,并能够在 css 文件中编辑长度/宽度。lg.png 与 index.html 和 style.css 位于同一文件夹中
Tried looking online for this answer but can't seem to get any luck.
试图在网上寻找这个答案,但似乎没有任何运气。
HTML:
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
" http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<head>
<title>yournetid</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<img id="my_image" src="lg.png" alt="image error"/>
<body>
<p>
Here's some awesome pictures!
</p>
</body>
CSS:
CSS:
body {
}
}
img#lg background:url(lg.png);
width:200px;
height:100px;
img#lg background:url(lg.png);
width:200px;
height:100px;
回答by sundance
Use a div
and set the background
property:
使用 adiv
并设置background
属性:
HTML:
HTML:
<div class="my_image"></div>
CSS:
CSS:
.my_image
{
background:URL('path/to/img.png');
width:100px;
height:100px;
}
回答by dev7
You are trying to use CSS selector img#lg
which makes no sense. You are telling CSS to look for an image with id of 'lg' but you did not set any id to your image.
您正在尝试使用img#lg
没有意义的CSS 选择器。您告诉 CSS 查找 ID 为 'lg' 的图像,但您没有为图像设置任何 id。
Also, setting the background-image:ur(lg.png)
is not the same as <img src='lg.png'>
.
此外,设置background-image:ur(lg.png)
与<img src='lg.png'>
.
To fix it:
要解决这个问题:
- Add id to your image
- Target the id in your CSS.
- 将 id 添加到您的图像
- 在 CSS 中定位 id。
Change your HTML:
更改您的 HTML:
<img id="my_image" src="lg.png" alt="image error">
CSS:
CSS:
#my_image {width:200px; height:100px; }
If you wanted to change CSS properties of ALL images, you'd use the following:
如果您想更改所有图像的 CSS 属性,您可以使用以下内容:
img {width:200px; height:100px; }
Hope this helps!
希望这可以帮助!