vplusm
vplusm

Reputation: 59

CSS combine two classes

I have 4 pictures in a horizontal line. The first 3 pictures have a margin-right: 20px;. Except for the last pictures which has no margin at all. This is how I did it, which I feel could be done better:

.threeimg {
margin-right: 20px;
border: 1px solid #cfcfcf;
border-radius: 6px;
background-color: white;
padding: 8px; }


.lastimg {
border: 1px solid #cfcfcf;
border-radius: 6px;
background-color: white;
padding: 8px; }

Any way to clean this up? Please don't be too hard on me, I literally started learning HTML&CSS 3 days ago.

Upvotes: 0

Views: 19036

Answers (4)

Bartek Bielawa
Bartek Bielawa

Reputation: 572

I always try to write my code simple as it's possible, especially the html code. Cooperation with backend coder will be easier. I remove class no-margin and use first-child atribute. The code is below, try it.

CSS

  .image {
        margin-left: 20px;
        border: 1px solid #cfcfcf;
        width: 100px;
        border-radius: 6px;
        background-color: white;
        padding: 8px;
    }
    .image:first-child {
        margin-left: 0;
    }

HTML

<img src="http://goo.gl/UEZSH" class="image">
<img src="http://goo.gl/UEZSH" class="image">
<img src="http://goo.gl/UEZSH" class="image">
<img src="http://goo.gl/UEZSH" class="image">

DEMO

http://jsfiddle.net/ppqCD/

Upvotes: 1

Jack Wong
Jack Wong

Reputation: 1

.img {
    margin: 0;
    border: 1px solid #cfcfcf;
    border-radius: 6px;
    background-color: white;
    padding: 8px; 
}

.threeimg {
    margin-right: 20px; 
}

We have more example here. http://www.html5database.com/example-css.php

Upvotes: 0

user1976613
user1976613

Reputation:

Use the css pseudo-class selectors

img {
    margin-right: 20px;
    border: 1px solid #cfcfcf;
    border-radius: 6px;
    background-color: white;
    padding: 8px; 
}

img:last-child {
    margin-right:0px;
}

Upvotes: 0

Sourabh
Sourabh

Reputation: 8482

Do it like this: DEMO

CSS

.image {
    margin-right: 20px;
    border: 1px solid #cfcfcf;
    width: 100px;
    border-radius: 6px;
    background-color: white;
    padding: 8px;
}
.no-margin {
    margin-right: 0;    
}

HTML

<img src="http://goo.gl/UEZSH" class="image">
<img src="http://goo.gl/UEZSH" class="image">
<img src="http://goo.gl/UEZSH" class="image">
<img src="http://goo.gl/UEZSH" class="image no-margin">

EDIT

Note: The .no-margin class should be below the .image class because of the cascading nature of CSS

Upvotes: 7

Related Questions