Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select the first paragraph in a div with a specific class (CSS 2)

I have a <div> containing many <p> elements and need to apply some style only to the first <p> inside every <div> with a specific class (cnt).

Please note this question may appear similar to others on SO, but the role I need should apply only for class cnt, which makes it different.

//I use YUI 3 Reset and Grid:
<link href="http://yui.yahooapis.com/3.4.0/build/cssfonts/fonts.css" rel="stylesheet" type="text/css" />
<link href="http://yui.yahooapis.com/3.4.0/build/cssgrids/grids.css" rel="stylesheet" type="text/css" />

        <div class="cnt">
             <p>Number 1</p>
             <p>Number 2</p>
             <p>Number 3</p>
        </div>


            // I'm using this class without success!"
           .cnt p:first-child
            {
                background-color:Red;
            }

    // Other classes could create some conflict
    .cnt p
    {
        margin: 10px 0px 10px 0px;
    }
    .cnt h2, .cnt h3, .cnt h4, .cnt h5, .cnt h6
    {
        font-size: 16px;
        font-weight: 700;
    }
    .cnt ul, .cnt ol
    {
        margin: 10px 0px 10px 30px;
    }
    .cnt ul > li
    {
        list-style-type: disc;
    }
    .cnt ol > li
    {
        list-style-type: decimal;
    }
    .cnt strong
    {
        font-weight:700;   
    }
    .cnt em
    {
        font-style:italic;
    }
    .cnt hr
    {
        border:0px;
        height:1px;
        background-color:#ddddda;
        margin:10px 0px 10px 0px;
    }
    .cnt del
    {
        text-decoration:line-through;
        color:Red;
    }
    .cnt blockquote 
    {   margin: 10px;
        padding: 10px 10px;
        border: 1px dashed #E6E6E6;
    }
    .cnt blockquote p
    {
        margin: 0;
    }

PS: I need it in CSS 2 (neither the less CSS3 :first-of-type works great)

like image 731
GibboK Avatar asked Sep 19 '11 15:09

GibboK


People also ask

How do I select a specific paragraph in CSS?

The most basic of the selectors is an element selector. For example, paragraphs in an HTML document are represented by the p element and wrapped in <p></p> tags. To select all paragraphs in a document we would use the following selector. To select all level 1 headings we would use the h1 selector.

How do you select the first section in CSS?

The :first-of-type selector in CSS allows you to target the first occurence of an element within its container. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.


1 Answers

Your example should work fine

Demo

Alternate method

Live Demo

Try using the first-of-type selector.

.cnt p:first-of-type{
    background-color:Red;
}

It is a CSS3 selector and wont work on IE8 however.

like image 170
Loktar Avatar answered Oct 18 '22 18:10

Loktar