Skip to main content

Using Selectors In CSS With Examples

 If you are new to CSS you may find trouble of using examples, I've written CSS and HTML together; pls check this link  it might help you in solving that problem. For intermediate and advanced learner, there would be no problem. Below examples are all checked in a browser and they work. I used Atom editor and Google Chrome browser (sometimes Safari too) for below examples.

Tag selector

These tags (body, h1, div, aside, article, etc.,) are HTML elements, they could be selected directly without putting any period (.), hash (#) or asterisk (*). See example below:

body {
background-color: #ddd;
color: #E06C6F;
}

Class selector

A CSS class start with a period, and you can assign a CSS class to a number of HTML elements.

.orange {
color: #f3360c !important;


}

Using same Class for different result

.orange {
color: red;
background-color: yellow;
}

p.orange {
color: green;
}

<h1 class="orange"> Heading </h1>
<p class="orange"> This is a paragraph </p>

First we wanted our text to be red, later on without changing Class we thought to change paragraph color to be green, so we used "p.orange" to select that paragraph and the Class.

Multiple classes

You may use multiple classes (single-space-separated) for an element, check below example:

.good {color: red;}
.bad {text-decoration: underline;}
.ugly {background-color: yellow;}
.the-movie {text-transform: capitalize;}

<p class="good bad ugly the-movie">
This is a paragraph.
</p>

ID selectors

ID is unique to each element, like Class you can't assign same ID to many elements. It is exactly works like Class, only Hash (#) is used instead of Period (.).

#orange {
color: #f3360c !important;
}

Using same ID for different result: it works exactly like Class (see above example, you just need to replace PERIOD with a HASH. But thing is we can't use same ID for more than one element, so better use Class.

Group selector

You can select many Tags, IDs and Classes all at once, check below example:

p, .orange, h1, #title {
color: #f13e08; /*red*/
}

<h1> This is a heading </h1>
<h2 class="orange"> This is second heading</h2>
<h3 id="title"> This is third heading</h3>
<p> This is a paragraph </p>

Asterisk (*) selector

It is called Wild Card or Universal selector for all HTML Tags (not for ID and Class), it selects every Tag. See example: h1, h2, h3 and p, all turn blue in text color.

* {
color: blue;
}

<h1> This is a heading </h1>
<h2> This is second heading</h2>
<h3> This is third heading</h3>
<p> This is a paragraph </p>

Descendent selectors

It is combination of two or more selectors, each is separated by a space (single space). In above example where we used "p.orange for color green" wasn't Descendent selector, 'coz there was no hierarchy in it.

Example 1 with Class and Tag

.post {
background-color: yellow;
}

.post h1 {
color: red;
}
.post p {
color: blue;
}

<div class="post">
<h1>Heading</h1>
<p>This is a paragraph.</p>
</div>
<p>This is second paragraph.</p>

Example 2 with Class and Class

.post {
background-color: yellow;
}

.post .head {
color: red;
}
.post .para {
color: blue;
}

<div class="post">
<h1 class="head">Heading</h1>
<p class="para">This is a paragraph.</p>
</div>
<p>This is second paragraph.</p>

Child selector

Select all the children of same parent. Space between selectors is optional "p > strong" and "p>strong" work in the same way.

p > strong {
color: red; /*select all the children of p*/
}

<div>
<p> This is <strong>very</strong> beautiful.</p>
<p> <strong> And</strong> </p>
<p> This is <em>really <strong>very</strong> </em>beautiful.</p> <!--Third para doesn't get selected-->
</div>

Difference between Descendant and Child selector

In above example "third paragraph" doesn't get selected 'coz it's not child of <p> element, but if you use below CSS for Descendant, all the paragraphs get selected.

p strong {
color: red; /*select all the descendants of p*/
}

Child selector again (pseudo classes)

:first-child, :last-child, :nth-child(), :first-of-type, :last-of-type, :nth-of-type()
In below example I tried to explain child-pseudo-classed in CSS comments.

p:first-child{color: red;} /*first child of other element*/
p:last-child {color:blue;}/*last child of other element*/
li:nth-child(3) {color: green;} /*third child of other elment*/
li:first-of-type {text-transform: uppercase;} /*works like first-child*/
li:last-of-type {color: yellow;} /*works like last-child*/
li:nth-of-type(2) {color: red;} /*works like nth-child()*/

<!--first part-->
<div>
<p>Hello God! Where do you live?</p>
<ul>
<li>in sky? </li>
<li>above sky?</li>
<li>beyond the <strong>sky?</strong></li>
<li>perhaps at some distant star?</li>
</ul>
<p>I am not able to <strong> understand.</strong></p>
</div>
<!-- here is second part-->
<div>
<p>God didn't answer, so I assume.</p>
<ul>
<li>It'll take time. </li>
<li>I'm not old enough.</li>
<li>I didn't ask <strong>correctly</strong></li>
<li>I'll ask again.</li>
</ul>
<p>Some day I'll get <strong>the answer.</strong></p>
</div>

Adjacent Sibling selector

Select the second selector only, if both are the children of same parent. Space between selectors is optional "h1 + p" and "h1+p" work in the same way.

h1+p {
color: red; /*only first paragraph turns red*/
}

<div>
<h1>Heading</h1>
<p>This is a paragraph.</p>
<p> This is second paragraph</p> <!-- doesn't get selected-->
</div>

Pseudo Classes and Elements

They are built in Classes and Elements that's why they are called "Pseudo (just for a name sake)"; you just start using them.

Pseudo Classes

Rule- single colon (:) is used.
Usage- selector:pseudo-class {property:value;}
Few are- a:link, a:visited, a:hover (or, selector:hover), selector:focus (mainly used for input field, ie., input:focus), a:active
Others are experimental (not for production), so I'm leaving them for now.

Example (a:link, a.class:link or .class:link)
It helps in changing the color of a hyperlink (which is blue by default).

a:link {
color: red;
}

a.ext:link {
color:green; /*you may also use .ext:link*/
}

<a href="http://example.com/"> a link</a><br />
<a href="http://example.com/" class="ext"> a link with class</a>

Example (a:visited, a.class:visited or .class:visited)
It helps in changing the color of already visited hyperlink.

a:visited {
color: yellow;
}

a.ext:visited {
color:red; /*you may use .ext:visited also*/
}

<a href="http://example.com/"> a link</a><br />
<a href="http://example.com/" class="ext"> a link with class</a>

Example (a:hover, a.class:hover or selector:hover)

Hover for hyperlinks

a:hover {
background-color: #ddd;
}

a.ext:hover {
color: #fff;
background-color: #000;
}

Hover for other selectors

body:hover {
background-color: #f7f7f7;
}

p:hover {
background-color: pink;
}

.para:hover {
color: white; /* you may use .para:hover also*/
background-color: red;
}

<body>
<p> This is a paragraph </p>
<p class="para"> This is second paragraph </p>
</body>

Example (input:focus or selector:focus)

input:focus {background-color: yellow;}
input.ok:focus {color:#fff; background-color: black;} /*you may also write .ok:focus also*/

<input type="text" placeholder="write ur first name" />
<br />
<input type="text" class="ok" placeholder="write ur last name" />

Example (a:active)

It comes into action the moment a person clicks on a hyperlink and hold on to that (without releasing the mouse).

a:active {color: green;}

<a href="http://www.example.com"> Visit this website </a>

Pseudo Classes with Descendant Selectors

nav a:link { color: red;}
.social-links a:link {color: green;}
/* likewise you can do for :hover, :visited, :active*/

<nav>
<a href="#home"> Home </a> | <a href="#about"> About</a>
</nav>
<br />
<div class="social-links">
<a href="#twitter"> Twitter </a> | <a href="#facebook"> Facebook </a>
</div>

Pseudo Elements

Rule- double colon (::) is used in CSS3.
Usage- selector::pseudo-element {property:value;}
Few are- ::after, ::before, ::first-letter, ::first-line, ::selection
Others are (which I'm not using)- ::cue, ::backdrop, ::placeholder, ::marker, ::spelling-error, ::grammar-error.

Example (::after)

p::after {
content: " And nothing more."
}

<p> This is a paragraph. </p>

Example (::before)

(1)

p::before {
content: " Yes."
}

<p> This is a paragraph. </p>

(2)

p.happ::before {
content: " Yes."
}

<p class="happ"> This is a paragraph. </p>

Example (::first-letter)

p::first-letter {
color: red; font-weight: 900;
}

<p> This is a paragraph. </p>

Example (::first-line)

p::first-line {
color: red; font-style: italic;
}

<p>
This is a first line. <br />
This is second line. <br />
This is third line. <br />
</p>

Example (::selection)

This CSS works when we select some text, in below example, after selection text turns red with black background.

p::selection {
color: red; background-color: black;
}

<p> Blah blah blah. </p>

Attribute selectors

Usage- selector[attribute]{property:value;}

In attribute selectors, there are three things (though they are many) to understand first: ^,$, and *.

^="to begin with", $="to end with", *="match this". Lets start with an easy example.

Easy example

a[href="http://example.com/"] {color: red;}

<a href="http://example.com/"> Visit example.com</a> <!-- text turns red-->

Now let's check out ^, $ and * just by an example.

a[href^="https"] {color: green;}
a[href*=".pdf"] {color: red;}
a[href$=".gif"] {color: yellow;}

<p>
<a href="https://example.org/"> Visit example.org</a> <br />
<a href="http://example.com/some.pdf"> Download pdf</a> <br />
<a href="http://example.com/img.gif"> Download a gif image </a>
</p>

Attribute selectors are good in placing a little "hyperlink or pdf" image before the beginning of the text, and this is possible by using "background-image" property in CSS.

More example for Attribute Selectors

Example (Tag[class])

p[class]{font-size: 50px;}
.good {color: red;}
.bad {text-decoration: underline;}

<p class="good bad">
This is a paragraph.
</p>

Example (Tag[alt])

img[alt]{border: 5px solid red;}

<img src="https://images.pexels.com/photos/238364/pexels-photo-238364.jpeg" width="100" height="100" alt="public image" />

Example (*[title])

*[title]{color: red;}

<h1 title="Hi!"> Heading 1</h1>
<p title="Hello!"> Hover over this line. </p>

Example (*[href][title])

*[href][title]{text-transform: uppercase;}

<p>
<a href="http://example.com/" title="go baby"> visit this </a>
</p>

One last thing

To check browsers support to selectors, pls visit: https://www.quirksmode.org/css/selectors/ and https://caniuse.com/. If you prefer other websites pls let me know in comments.

Comments

Popular posts from this blog

Golden Rule Of Three Years To Get Success

Give yourself completely to whatever you like for three years -- let it be your career, business, health or any other thing of life. Why three years, exactly? Because what is the advantage of sticking to something which isn't giving any result. Time is precious, don't waste if the results aren't coming. Why not less than three years? If we spread these three years for success, we can assume first year is dominated by getting knowledge of the field, second year dominated by execution, and the third year comes the maturity where knowledge and experience of execution strike for success.  As an exeption we can stretch these three years into five or six years -- only when there are uncontrollable issues like of health or circumstantial issues.

108 Names Of Shri Surya From Mahabharata

Surya (Sun) is the most important planet as well as a deity. Worshiping Surya increases prana-shakti (life-force), it rays destroy many diseases and it is the biggest source of never ending energy. There is a Strota, called Surya-Kavach, it is chanted for protection, as a deity his protection is very strong — remember the case of Karna in Mahabharata, he was invincible due to Surya-Kavach. This Surya-Kavach wasn’t as it is shown in movies, it was a Mantrik protection which Karna had and on Indra request he promised not to use it in the war. We take note of popular deities, but Surya as a deity is not lesser than others — though there are less Sanskrit literature on Surya (as I know), but whatever it is, like Surya Kavach and Aditya Hriday Strota, I think, is very potent. English Name | हिंदी नाम 1) Om Suryaay Namah | ॐ सूर्याय नम: 2) Om AryMane Namah | ॐ अर्यमणे नम:

Name List Of 64 Yogini / चौँसठ योगिनी

It is a list of 64 Yogini, if you want these names in Stotra form you can get from another post of this blog. These names are very useful for doing, Jaap, Puja, Tarpan, and Havan. These names are also used in making 64 Yogini Yantra in which there are 64 squares and in each square, name of each Yogini is written, then everyday worship of this Yantra starts.  For Pujan (Poojan): ओं ---------- देव्यै पूजियामि नम: ! (e.g., ओं गजानना देव्यै पूजियामि नम: ! ) For Tarpan: ओं ---------- देव्यै  तर्पयामि नम: ! (e.g., ओं गजानना देव्यै  तर्पयामि नम: !) Together Pujan+Tarpan: ओं ---------- देव्यै   पूजियामि / तर्पयामि नम:: ! (e.g., ओं गजानना देव्यै   पूजियामि / तर्पयामि नम:: ! ) For Jaap : ओं ---------- देव्यै नम:! (e.g., ओं गजानना देव्यै नम:!) For Havan:  ओं ---------- देव्यै स्वाहा ! (e.g., ओं गजानना देव्यै स्वाहा !) Note: in the empty space ( ---------- ) you can fill the name of each yogini for each time. List of 64 Yogini / चौँसठ योगिनी For better readability I put this list in four parag

Moringa Soup 🍲

I don't like taste of Moringa but as it has a lot of health benefits, I think it should be eaten once in a week or in fifteen days. Health benefits of Moringa leaves Though bitter in taste, it is considered rich in nutrients and antioxidants. It has anti-inflammatory properties, also it is supposed to lower down cholesterol and blood sugar level. It is considered to have numerous health advantages. Where to find Moringa?  Available at any vegetable shop, weekly mandi market or search 'em at online stores. Moringa Soup Ingredients: Moringa cut into 2 inches pieces, onions, garlic, masoor dal (लाल वाली), ginger, shimla mirch, green chili, rock salt, kali mirch, and turmeric powder.

Essential Nyas For A Sadhak To Do Everyday

Nyas means to establish something (Devi / Devta energy) in our body: it purifies our body and makes our body and mind worthy of chanting a mantra / stotra. A Sadhak should do भूत-शुद्धि, बहिर्मातृका न्यास, अन्तर्मातृका न्यास, and षोढा-न्यास daily, 'coz we worship Devta by becoming a Devta, and in that Nyas helps us a lot. In every mantra generally many kinds of Nyas are given prior to chanting a mantra, they are usually shorter and doesn't take much time. They are essential and shouldn't be skipped. These  भूत-शुद्धि, बहिर्मातृका न्यास, अन्तर्मातृका न्यास, and षोढा-न्यास take comparatively longer time duration.  भूत-शुद्धि means purification of five elements in our body, that is Earth (Prithvi), Water (Jal), Fire (Agni), Air (Vayu), and Ether (Aakash). बहिर्मातृका Nyas and अन्तर्मातृका Nyas, establish  "energy of our VarnMala" in our body-parts and in our chakras respectively.   षोढा-न्यास is of two types Lagu Shoda Nyas and Maha Shoda Nyas.

Nutritional Diet Plan (Raw) To Any Disease

It may help in any kind of chronic disease -- we just need to learn how to prepare them.  Things to eat / drink: Smoothie Salad / fruits / vegetables Steamed vegetables (when raw vegetables are difficult to eat.) Juices Soup Coconut Milk Cold-pressed edible virgin coconut oil (to be taken as raw one to three teaspoons a day.) Taste enhancers: Chutney / Tahini / Kokum etc. Crushed "garlic, ginger, raw turmeric, raw amala, green chilly" (It is v. good) Banana Icecream (sometimes, not to be eaten regularly, as it may slow down digestive fire.) Once in a day Moon Dal and brown rice. Soaked peanuts and dry-fruits in lower quantity initially. We need to choose what to eat in breakfast, lunch, evening-snacks and dinner. In raw diet, we need to eat a lot.  Just open Youtube and search for "Smoothie" you may get plenty of videos, like that you can search for Soup, Chutney and other items. Try to use above diet plan for a week. Also one needs to check nutritional deficiency f

Utkeelan Mantra & Stotra Vidhan Of Shri Batuk Bhairav

Below is Utkeelan Mantra & Stotra of Shri Batuk Bhairav. You can also get  Shap Vimochan & Shapoddhar Mantra / Stotra from here . Both go hand in hand for removing curse and unlocking Keelan of Shri Batuk Bhairav Mantras and Stotras. ।।  विनियोग  ।। ॐ अस्य श्रीबटुक-भैरवोत्कीलन-मन्त्र- स्योग्र-भैरवो ऋषिः, अनुष्टुप् छन्दः, श्रीभैरवो देवता, वं बीजं, ह्रीं शक्तिः, क्लीं कीलकं, मम सर्वाभीष्ट- सिद्धधर्थे बटुक-भैरवोत्कीलन-मन्त्र-जपे विनियोगः । ।।  ऋष्यादि-न्यास  ।। उग्रभैरव-ऋषये नमः शिरसि । अनुष्टुप् छन्दसे नमः मुखे । श्रीभैरव देवतायै नमः हृदि । वं बीजाय नमः गुह्ये । ह्रीं शक्तये नमः पादयोः । क्लीं कीलकाय नमः नाभौ । मम सर्वाभीष्ट- सिद्धघर्थे बटुक-भैरवोत्कीलन-मन्त्र-जपे विनियोगाय नमः सर्वाङ्गे । ।।  कर-न्यास  ।। ॐ अंगुष्ठाभ्यां नमः । ह्रीं तर्जनोभ्यां नमः । क्लीं मध्यमाभ्यां नमः । ऐं अनामिकाभ्यां नमः । हू कनिष्ठिकाभ्यां नमः । म्रां कर-तल-कर- पृष्ठाभ्यां नमः । ।।  षडङ्ग-न्यास  ।।  बटुकाय हृदयाय नमः । उमा-पुत्राय शिरसे स्वाहा । एकादश-रुद्रावताराय शिखायै वषट् । वीरभद्रावताराय कवचाय हुम् ।

Why Two Types Of Navratri Are More Popular

Navratri comes four times in a year: 1) In Chitra (Vasant) Maas, 2) In Sharad (Ashwin) Maas, 3) In Ashadha (आषाढ़) Maas, and 4) in Magh Maas. As it is written in the following Shaloka: चैत्रे आश्विने तथाषाढे, माघे कार्यों महोत्सवः। नव रात्रे महाराज! पूजा कार्या विशेषतः ।।  Generally, we are told that two Navratri are for public and rest two Navratri are called Gupt Navratri. These two Gupt Navratri are for the Sadhak --- but it isn't the exact fact. All four Navratri are for general public and for all dedicated Devi Sadhak, there is no secret. Fact is during the time of Chaitra and Sharad, weather changes a lot -- so there are chances of getting diseases. During Navratri due to fasting and purification, all kind of diseases can be avoided, that's why these two Navratri gained significance among public.