How can I use CSS to style multiple images differently?

女生的网名这么多〃 提交于 2020-06-25 00:57:06

问题


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.

I also understand, that I could style each image in the html tag, like this:

<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?


回答1:


You can give each image a class or id that will help you to define different css for each image like

<img src="" class="image1">
<img src="" class="image2">

in css file you can define

.image1
{
width:200px;
height:200px;
}
.image2
{
width:300px;
height:300px;
}



回答2:


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">



回答3:


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




回答4:


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;
}


来源:https://stackoverflow.com/questions/27697549/how-can-i-use-css-to-style-multiple-images-differently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!