Html 如何使用 CSS 为多个图像设置不同的样式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27697549/
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
How can I use CSS to style multiple images differently?
提问by cphil
I am basically styling a long essay with various images scattered throughout. I would like the first image to "float: left" and the second one to "float: right". I know that I can style the images like this:
我基本上是在设计一篇长篇文章,其中散布着各种图像。我希望第一个图像“浮动:左”,第二个“浮动:右”。我知道我可以像这样设置图像的样式:
img {
float: left;
}
This makes each image have the same style. How do I style each image differently? I tried to put each image in a different div class, so that I could style them differently, but it didn't work.
这使得每个图像具有相同的风格。我如何为每个图像设置不同的样式?我试图将每个图像放在不同的 div 类中,以便我可以对它们进行不同的样式设置,但是没有用。
I also understand, that I could style each image in the html tag, like this:
我也明白,我可以在 html 标签中设置每个图像的样式,如下所示:
<img src="ABCD.png" alt="Raoul Hausmann's ABCD" align="left" height="300px">
I keep hearing that it is best to keep style in the external style sheet (CSS), separate from the html. Is this a case where inline styling is necessary?
我一直听说最好将样式保留在外部样式表 (CSS) 中,与 html 分开。这是需要内联样式的情况吗?
回答by priya786
You can give each image a class or id that will help you to define different css for each image like
您可以为每个图像指定一个类或 id,以帮助您为每个图像定义不同的 css,例如
<img src="" class="image1">
<img src="" class="image2">
in css file you can define
在 css 文件中你可以定义
.image1
{
width:200px;
height:200px;
}
.image2
{
width:300px;
height:300px;
}
回答by Bill
Give your image a class and then you can style all images with that class like this:
为您的图像指定一个类,然后您可以使用该类为所有图像设置样式,如下所示:
.left {
border: solid 5px red;
float: left;
}
.right {
border: solid 5px blue;
float: right;
}
<img src="ABCD.png" class="left">
<img src="ABCD.png" class="right">
回答by Marius Vorster
All the above are fine, I would only suggest grouping the common settings of picture in this case so that the left/right classes only contains that what is different.
以上所有都很好,我只建议在这种情况下对图片的常用设置进行分组,以便左/右类只包含不同的内容。
/* Group the common attributesso that you only need to set it once */
.picture, .leftPicture, .rightPicture {
border: 2px dotted gray;
width: 200px;
}
.leftPicture {
float:left;
}
.rightPicture {
float:right;
}
回答by sanoj lawrence
Try this
尝试这个
img{width: 200px;height:200px;background-color: antiquewhite}
.left{float:left}
.right{float:right}
<img src="ABCD.png" alt="Raoul Hausmann's ABCD" class="left">
<img src="ABCD.png" alt="Raoul Hausmann's ABCD" class="right">
this will float two images one in left and another in right
这将浮动两个图像,一个在左边,另一个在右边