Finding elements by using pseudo-elements



Using pseudo-elements

Pseudo-elements allow you to insert content into the page in locations relative to the elements that the CSS is being applied to.

Using :first-child pseudo-element

The :first-child pseudo-element applies the specified styles to the first instance of the element that occurs in a list.

The following CSS will change the text color to green in the first paragraph element:

<head>
<style type="text/css">
    #div1 > p:first-child {
        font-size:35px;
        color:green;
        }
</style>
</head>
<body>
  <h3>pseudo-element SELECTOR (#div1 > p:first-child )</h3>
    <div id="div1">
        <p>Lorem Ipsum ...</p>
        <p>Lorem Ipsum ...</p>
        <p>Lorem Ipsum ...</p>
    </div>
</body>

Using :first-letter pseudo-element

The :first-letter pseudo-element will alter the style of the first letter in the specified element.

The following CSS will increase the size of the first letter in each paragraph element:

<head>
<style type="text/css">
    #div2 > p::first-letter {
        color:red;
        font-size: xx-large;
        }
</style>
</head>
<body>
  <h3>pseudo-element SELECTOR (#div2 > p::first-letter)</h3>
    <div id="div2">
        <p>Lorem Ipsum ...</p>
        <p>Lorem Ipsum ...</p>
    </div>
</body>

Using :before and :after pseudo-elements

The :before and :after pseudo-elements will add the specified content in front of or after the indicated element selector.

The following CSS code demonstrates the :before and :after pseudo-elements:

<head>
<style type="text/css">
    #div1 > p::before {
        content: ' THIS CONTENT ADDED BEFORE ';
        }
    #div2 >  p::after {
        content: ' THIS CONTENT ADDED AFTER ';
        }
</style>
</head>
<body>
    <h3>pseudo-element SELECTOR ( #div1 > p::before )</h3>
    <div id="div1">
        <p>Lorem Ipsum ...</p>
    </div>
    <h3>pseudo-element SELECTOR (#div1 >  p::after)</h3>
    <div id="div2">
        <p>Lorem Ipsum ...</p>
    </div>
</body>

Using :first-line pseudo-element

The :first-line pseudo-element alters the styles of the first line of a text element.

The following CSS will make the first line of the text green and larger:

<head>
<style type="text/css">
    #div4 > p::first-line {
        color:green;
        font-size: x-large;
        }
</style>
</head>
<body>
    <h3>pseudo-element SELECTOR (#div3 > p::first-line)</h3>
    <div id="div4">
        <p>Lorem Ipsum what are you saying <br />
            This is the second line
        </p>
    </div>
</body>

PROMOTIONS