user11137294
user11137294

Reputation:

Setup individual sizes for different images from .css

I know it is very basic, but I'm trying to figure out, how to give different sizes for different images from .css to .html if I have many images to setup sizes from .css.

If I have size for one image myimg1.png:

<img src="assets/image/myimg1.png"/>

in .css:

img{
  width: 212px;
  height: 95px;
}

then I'm not able to give different size for another one myimg2.png directly:

<img src="assets/image/myimg2.png" width="65" height="72" /> 

Guide or example would be useful

Upvotes: 0

Views: 52

Answers (2)

Lucas S.
Lucas S.

Reputation: 702

You are not using CSS selectors the right way.

img {

}

Means you will apply the style to all <img> HTML tags.

To differentiate between different <img> tags, you need to use CSS classes:

<img src="assets/image/myimg1.png" class="imgOne" />
<img src="assets/image/myimg2.png" class="imgTwo" /> 
.imgOne {
  width: 212px;
  height: 95px;
}

.imgTwo {
  width: 65px;
  height: 72px;
}

In your example, the HTML element's attributes width and height are overridden by the CSS img selector.

You can avoid this by either using the CSS as mentioned above, or by changing your HTML to:

<img src="assets/image/myimg2.png" style="width: 65px; height: 72px;" /> 

The content of the style attribute is basically CSS, and will take precedence over what's defined inside your CSS file.

Upvotes: 2

Shraddha
Shraddha

Reputation: 884

If you want to style different images differently and if you do not want to use class for every images then you can make use of :nth-of-type() selector like this:

/* Select first img element */
img:nth-of-type(1) {
...
}

/* Select nth img element */
img:nth-of-type(n) {
...
}

/* Select even positioned img elements */
img:nth-of-type(even) {
...
}

/* Select odd positioned img element */
img:nth-of-type(odd) {
...
}

For more explanation, please refer:
1. CSS Tricks - nth-of-type()
2. CSS3 structural pseudo-class selector tester

Upvotes: 0

Related Questions