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.

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

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 | ॐ अर्यमणे नम:

Shri Janaki Navami Vrat & Sita Anupras

 Sita is also known as Janaki, her festival that is Janaki Navami comes on Falgun Sudi Navami. This day is her birthday and she is worshiped, इस दिन सीताजी को समस्त पूजा सामग्री से पूजा कर सुहाग की वस्तुओ से उनका श्रृंगार करना चाहिए जैसे की बिंदी, मेहँदी, चूड़ी, काजल, लिपस्टिक, महावर, इत्यादि। ऐसा कहा जाता है की सुहाग की वस्तुओ से पूजा करने पर पूजा करने वाली महिलाओ का भी सुहाग बना रहता है। I think she should be worshiped with Ram, Lakshman & Hanuman ji, ‘coz she likes them a lot. Double Benefit

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.

Devi Lalita Vrat & Puja Vidhi

 This festival is celebrated on Bhadon Vadi Chhath. It is for Devi Lalita, this day she is worshiped. Women worship Devi Lalita by Vrat and Puja, ‘coz they want to see the Goddess as their friend. And as a friend Devi is supposed to solve their problems of life and fulfil other genuine wishes. गंगा द्वारे कुशावंते विल्वके नील पर्वते ॥ स्नात्वा कनखले देवि हरं लब्धवतीं पतितं ॥ ललिते सुभगे देवी सुख सौभाग्य दायिनी ॥ अनंतं देहि सौभाग्यम मह्यं तुम्भ नमोनमः:॥ In her worship, above stotra is chanted which means — हे देवी ! आपने गंगाद्वार, विल्वक, नीलपर्वत एवं कनखल इत्यादि पवित्र तीर्थो में स्नान कर भगवान शंकर को पति के रूप में वरण किया है, हे सौभाग्यदायिनी देवी ललिता आपको नमस्कार करता हूँ (करती हूँ ) ।

Mantra To Remove Poverty & Attract Lakshmi On Diwali

 Here are few things that previous generations used to do on Diwali. Mantra to remove poverty: This mantra is often chanted to beat away the poverty from the home. This is ritualistic where people imagine “poverty” and other kinds of negativity are going away and home is getting purer and cleaner to attract goddess Lakshmi. काने भेड़े दुखदायी दरिद्र तू मेरे घर से जा अब भाग ॥ देवी भगवती लक्ष्मी आई, तज घर मेरा और जा भाग ॥ डंडा बजाऊ मार लगाऊ नहीं तो जा अब भाग ॥ लक्ष्मी जी का वास हो गया मेरे यहाँ, तेरा नहीं निस्तार ॥ Mantra to attract Lakshmi:

18 Types Of Puja (Worship) Acc. To Fetkarini Tantra

Puja enhances our devotion to our Deity, and it is not an expensive affair we can learn to do it ourselves. Puja makes our heart-center (Air element) stronger, as our devotion increases it is bound to be happen. It is written in Fetkarini Tantra, about 18 kinds of worship (Puja). I think during Navratri, Holi, Deepawali (Lakshmi), Ganesh Chaturthi, MahaShivRatri and during all major festivals, Panchopachar Puja isn't sufficient one should go for either Shodosopchar Puja (16 types) or below 18 types of Puja. Try to do this in Navratri or at the time of Ganesh Chaturthi, because during these two festivals most of the Hindu do Murti Visarjan (point 18). आसनावाहनं चार्घ्य, पाद्यमाचमनं तथा। स्रानं वासोपवीतिं च, भूषणानि च सर्वशः ।। गन्धं पुष्पं तथा दीपं, धूपोऽत्रं चापि तर्पणम्। माल्यानुलेपनं चैव, नमस्कारो विसर्जनम् ।।  अष्टादशोपचारैस्तु, मातृ पूजां समाचरेत् ।। Means:1 आसन, 2 आवाहन, 3 अर्घ्य, 4 पाद्य, 5 आचमन, 6 स्नान, 7 वस्त्र, 8 उपवीत (जनेऊ), 9 आभूषण, 10 गन्ध, 11 पुष्प, 12 धूप, 13 दीप, 1