Domanda

I have a three divs that has same classes assigned to it. What I want to do is to apply a separate style to the first div and different to other two.

   <div class="news_post">...</div>
<div class="news_post">...</div>
<div class="news_post">...</div>

Any suggestions on what is the right way to go about it?

È stato utile?

Soluzione

Working DEMO

.news_post:first-child {
  background: red;
}

.news_post {
  background: green;
}

If you want to customize any element in future

.news_post:nth-child(2) { // 2 represents the position
  background: blue;
}

Altri suggerimenti

You can use Pseudo Element Selectors.

:nth-child()

:first-child

:last-child

If you only want to apply different style on First Div Try this :

.news_post{
    background-color:black;
    height:20px;
    width:200px;
}
.news_post:first-child
{
    background-color:red;
}

Working Demo

If you want to apply different-different style on all three divs, Try this :

.news_post{
    height:20px;
    width:200px;
}
.news_post:nth-child(1)
{
   background-color:red;
}

.news_post:nth-child(2)
{
   background-color:green;
}

.news_post:nth-child(3)
{
   background-color:black;
}

Working Demo

You can try this:

.news_post:nth-child(1)
{
   background:#ff0000;
}

.news_post:nth-child(2)
{
   background:blue;
}

.news_post:nth-child(3)
{
   background:black;
}

Try pseudo class.

.news_post:first-child
.news_post:last-child

More about pseudo classes in css

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top