CSS Selectors


Element Type Selector

Element type selector is used to select all the elements based on the tag you defined in your stylesheet. For Example, here I style button and textbox by selecting them using Element Type Selector in stylesheet.

index.html

<div>I am From America</div>
<p>I am from Pakistan. We are peaceful nation</p>
<br>
    <span>I am from Canada</span>

style.css

p{
    background-color:green;
    padding:10px;
    color:white;
    font-size:18px;
    font-family:calibri,sans-serif;
}

Show Demo on JsFiddle

ID Selector

You can select any element/tag by specifying its ID. ID is unique. No two elements have same ID. So, ID Selector select an element/tag according to your specified ID Selector. ID Selector starts with pound/hash symbol (#) and then follow the ID of element/tag

index.html
<p>Hello</p>
<p id="StyleMeWell">Hello Again</p>
<p>Hello Again and Again</p>
<p>Hello Again and Again</p>
<p>Hello Again and Again</p>

style.css

#StyleMeWell{
    background-color:#cc0000;
    color:white;
    font-family:calibri,sans-serif;
    font-size:18px;
    padding:10px;
}

Show Demo on JsFiddle

Universal Selector

Sometime, you want to apply style to every element of webpage. To do this CSS provide Universal Selector (*).

index.html

<div>Hello From Division</div>
<p>Hello From Paragraph</p>
<b>Hello From Bold Tag</b><br>
We all are sized 32px because of * Universal Selector
style.css
*{
    font-size:32px;
}

You should avoid using Universal Selector because of its performance cost.

Show Demo on JsFiddle

Descendant Selector

You might want to style an element if and only if it was descendant(child) of specific element. The Syntax Become Like this

Parent Child (Whether Grand Child, Direct Child)

index.html

<div>
  <a href="">I am Direct Child of Div</a>
  <p>
    <a href="">I am child of P But Grand Childeren of Div</a>
  </p>
</div>
<a href="">I am not styled because I am not descendant of div element</a>
style.css
div a{
    color:orange;
}

In this example, all the list that come within div and they will also styled even they are child of some other element that reside in div.

Show Demo on JsFiddle

Child Selector

You might want to style an element if it is direct child of your specified element. So, the General syntax will be

Element > Child (Direct Child Not Grand Child)

index.html

<div>
  <a href="">I am Direct Child of Div</a>
  <p>
    <a href="">I am child of P But Grand Childeren of Div</a>
  </p>
</div>
style.css

div > a{
    color:orange;
}

Show Demo on JsFiddle

Difference Between Descendant Selector and Child Selector

The following Image describe the whole difference. This is actually a Question on StackOverFlow. You can find this question on Stackoverflow

Stackoverflow

Pseudo Classes

Pseudo Classes are Introduced to select or access elements information that is outside the scope of DOM (Document Object Model).

Pseudo classes classify elements based on something other than name, attributes, or content and, usually, something that cannot be deduced from the DOM tree. Exceptions to the rule are :first-child, which can be deduced from the DOM tree, and :lang(), which can sometimes be deduced from the DOM tree.

The List of Pseudo Classes are here

:link Denotes unvisited links. a:link selects all unvisited links.

:visited Denotes visited links. a:visited selects all visited links.

:active Denotes an active link. Active Link mean when the mouse button is pressed down and a:active selects all active links.

:hover Denotes a link on which the mouse is over. a:hover select the link on which the mouse is over.

index.html

<a href="dlalpha.wordpress.com">Visited Link</a>
<a href="http://www.w3schools.com/about/default.asp">Unvisited Link</a>
<br>
    <ul>Things To TRY
        <li>Hover over the link</li>
        <li>Click the link but let the mouse button clicked</li>
style.css

/* unvisited link */
a:link {
    color: #FF0000;
}

/* visited link */
a:visited {
    color: #00FF00;
}

/* mouse over link */
a:hover {
    color: #FF00FF;
}

/* selected link */
a:active {
     color: #0000FF;
}

Show Demo of :link, :visited, :active, :hover on JsFiddle

:focus Denotes the text field / input element when it get the focus. a:focus select the input that has the focus.

index.html

<input type="text" id="textbox" />
Click the text box to focus it
style.css

input[type='text']:focus{
    border:2px solid yellow;
    padding:10px;
    font-size:18px;
}

Show Demo on JsFiddle

:checked Denotes an option box or checked box whose checked attribute is set. Input[type=’checkbox’]:checked select all the checkboxes which are checked by user.

index.html

<input type="checkbox" id="checkbox" />
<p>This is really awesome</p>
style.css

input[type='checkbox']:checked + p{
    background-color:yellow;
    padding:10px;
    color:black;
    font-size:32px;
}

Show Demo on JsFiddle

:lang(language) Denotes a HTML Element whose lang attribute is set to a language equal to the argument of :lang(language). p:lang(en) selects all the paragraph whose lang attribute is set to en (Full English).

 index.html

<h2>French Paragraph is highlighted</h2>
<p lang="en">
    Most students like the freedom they have in college. Usually college students live on their own, in the dormitory or in an apartment. This means they are free to come and go as they like. Their parents can’t tell them when to get up, when to go to school, and when to come home. It also means that they are free to wear what they want. There are no parents to comment about their hair styles or their dirty jeans. Finally, they are free to listen to their favorite music without interference from parents.
</p>
<p lang="fr">
    1) Toute personne a droit à l'éducation. L'éducation doit être gratuite, au moins en ce qui concerne l'enseignement élémentaire et fondamental. L'enseignement élémentaire est obligatoire. L'enseignement technique et professionnel doit être généralisé; l'accès aux études supérieures doit être ouvert en pleine égalité à tous en fonction de leur mérite.
 2) L'éducation doit viser au plein épanouissement de la personnalité humaine et au renforcement du respect des droits de l'homme et des libertés fondamentales. Elle doit favoriser la compréhension, la tolérance et l'amitié entre toutes les nations et tous les groupes raciaux ou religieux, ainsi que le développement des activités des Nations Unies pour le maintien de la paix.
 3) Les parents ont, par priorité, le droit de choisir le genre d'éducation à donner à leurs enfants.
</p>
style.css

p:lang(fr){
    background-color: #F5F5DC;
    padding:10px;
    font-family:calibri,sans-serif;
}

Show Demo on JsFiddle

:not Selects all the elements of type specified before :not pseudo classes. For Example, div:not(“#Advertisment”). Select All the div elements except the Div with Advertisement ID.

:nth-child(formula) is used to select nth child of parent element. You can also pass odd or even as argument. The odd argument selects odd child element or parent element. You can see odd or even and nth-child demo on JsFiddle. For Example, I want to select Every Third Element (3, 6, 9). So, I have to apply Formula. To do this

 index.html

<li>Plants</li>
<li>Trees</li>
<li>Animal</li>
<li>Birds</li>
<li>Humans</li>
<li>Mammals</li>
<li>Lion</li>
style.css

li:nth-child(3n + 1){
    background-color:orange;
    color:white;
    padding:10px;
}

Show Demo on JsFiddle

Master nth-child at

only-child Select the element if it is the only child of its parent. p:only-child select the paragraph which is the only child of its parent element.

index.html

<ul>
 <li>I am afraid as I am Alone</li>
</ul>
<ul>
 <li>Apple</li>
 <li>Mango</li>
</ul>
style.css

li:only-of-type{
background-color:#cc0000;
color:white;
font-size:32px;
}

 

Show Demo on JsFiddle

only-of-type Select the element which is the only  element of specified type. For Example

index.html

<ul>
	<li>I am afraid as I am Alone</li>
</ul>
<ul>
	<li>Apple</li>
	<li>Mango</li>
</ul>
style.css

li:only-of-type{

background-color:#cc0000;
color:white;
font-size:32px;

}

Show Demo at JsFiddle

:first-of-type Selects the first element of the specified type

index.html

<p>Destructive Labs Alpha</p>
<p>Destructive Labs Alpha or DLAlpha is an accidental name of this blog. I think of this name when I was learning C#. I create this project locally on my computer to learn c#. As you know, when we are learning we break alot of things. So, this name is absolutely suitable for such kind of situtations.
style.css

p:first-of-type{
    font-size:32px;
    font-family:verdana,sans-serif;
    font-weight:bolder;
    text-decoration:underline;
    padding:10px;
    
}

 

Show Demo at Demo

::first-line Selects the first line of specified element. p::first-line select the first line of
paragraph. It is useful when you want to style first line of paragraph different from the
rest of paragraph

index.html

Most students like the freedom they have in college. Usually college students live on their own, in the dormitory or in an apartment. This means they are free to come and go as they like. Their parents can’t tell them when to get up, when to go to school, and when to come home. It also means that they are free to wear what they want. There are no parents to comment about their hair styles or their dirty jeans. Finally, they are free to listen to their favorite music without interference from parents.

 
style.css

p::first-line{
    font-size:32px;
}

Show demo at JsFiddle
::first-letter Selects the first letter/character of the element specified. p::first-letter selects
the first letter of paragraph. It is very useful when you want to make your first letter
larger.

index.html

<p>A quick brown fox jumps over the crazy dog</p>
style.css

p::first-letter{
    font-size:32px;
}

Show Demo at JsFiddle

::before It is used to insert some text or some kind of shape you want just before the element
you specified. For Example, blockquote::before{ content:”Note:”;} will insert “Note:” into each
blockquote element directly before the exisiting content. In addition to just adding content,
you can also specify other properties for formating. For Example, blockquote::before{ content:”Note”;font-size:32px;}.

You can also add images, audio, video, counter, string as well as open-quote and close-quote

 

index.html

<blockquote>A lie told often enough becomes the truth</blockquote>
style.css

blockquote::before{
content:"Lenin Says ";
    font-size:28px;
    
}

Show Demo at JsFiddle

::after It is used to insert some kind of text or some shape you want just after the element content
you specified. For Example, #emailSend::after{ content:”Thankyou for Contacting us”}. Just like
the ::before pseudo element you can also style it by defining some other properties.
#emailSend::after{ content:”Thankyou for Contacting us”;color:#fcfc0d; }

index.html

<p>
    Most students like the freedom they have in college. Usually college students live on their own, in the dormitory or in an apartment. This means they are free to come and go as they like. Their parents can’t tell them when to get up, when to go to school, and when to come home. It also means that they are free to wear what they want. There are no parents to comment about their hair styles or their dirty jeans. Finally, they are free to listen to their favorite music without interference from parents.
</p>
style.css

p::after{
    font-size:32px;
    display:block;
    content:"Thankyou For Reading our article";
    text-decoration:underline;
    color:red;
}

Show Demo at JsFiddle
::selection It is used to style the text/content you selected. For Example , By Default when you
select some text. It is highlighted in blue color. Using this ::selection pseudo element you can change
the color of selection. For More Detail visit w3Schools

index.html
Try To Select Me Using your mouse. I will be highlighed with red color and white font color.

 

style.css
::selection{
    background-color:#cc0000;
    color:white;
}
::-moz-selection{
       background-color:#cc0000;
    color:white;
}

Show Demo at JsFiddle

NOTE ONE OR TWO COLONS BEFORE PSEUDO ELEMENTS
CSS3 recommends one colon (:) before pseudo classes and two colons (::) before pseudo
elements as a way to tell the difference between the two. CSS3 also allows one-colon usage
on existing rules to be backward compatible with existing browsers, so most people will
continue to use one colon to be backward compatible with older browsers. All new pseudo
elements are required to have two colons.

 

Grouping Selectors

You can group selectors when you are applying same style to both. Consider the following example, in
which these two code block have the same declaration.

blockquote{
background-color:#fcfc0d;
font-size:32px;
}
p{
background-color:#fcfc0d;
font-size:32px;
}

In this Example, blockquote and p element have the save style. But, we have to write it two time
which increase the number of lines you have to write. So, We can combine or group these selectors
together easily

blockquote, p {
background-color:#fcfc0d;
font-size:32px;
}

These both have the same effect just the number of lines matter. So, you should always use the second model (Grouping Selectors) when you want to have two different selectors with the same style declaration.

Adjacent Sibling Selector

An adjacent selector is used to select an element if it is preceded by specific element. It is denoted by > symbol. For Example

div + h1 selects the h1 that immediately occurs after the div element.

index.html

<h1>I am not highlighted because I does not come after the div
</h1>
<div>Hello, I am really a div</div>
    <h1>I will be highlighter because I have just come after the div</h1>
<p>I am paragraph</p>
style.css

div + h1 {
    background-color:#fcfcd0;
}

Show demo at JsFiddle

Subsequent Sibling Selector

The subsequent sibling selector is just like the adjacent sibling selector except it selects all the h1 element (or the element you specify) that come after div ( or the element you specify). It is denoted by ~ (tilde) character. For Example div ~ h1 selects all the h1 that come after the div element.

index.html

<h1>I am not highlighted because I does not come after the div
</h1>
<div>Hello, I am really a div</div>
    <h1>I will be highlighter because I have come after the div</h1>
<p>I am paragraph</p>
<h1>I will be highlighter because I have come after the div</h1>
<h1>I will be highlighter because I have come after the div</h1>
style.css

div + h1 {
    background-color:#fcfcd0;
}

Show Demo on JsFiddle

Attribute Selector

Attribute Selector is used to select element based on the existence of the specified
attribute. For Example, a[title] selects all the hyperlink having title attribute
set to something. We can Also retrieve the value of attribute in the css using
attr() function.

a[title]:hover:after{
content:attr(title);
}

Show Demo on JsFiddle

Attribute Value Selector

Attribute Selector is used to select element based on the value specified.
For Example, a[title = “Google Plus”] selects all the hyperlink having title set to “Google Plus”

a[title="Google Plus"]:hover:after{
content:"Google+";
}

Show Demo on JsFiddle

Attribute Contains Value Selector

Attribute Selector is used to select all element which contain the specific value.
For Example, a[title *= “Contoso”] selects all the hyperlink which contain “Contoso” somewhere
in the title attribute. It is much flexible as compared to Attribute Value Selector because you
dont have to type the exact value of your selected attribute. You Can easily specify attribute contains
value selector by adding * (Asterik Sign) in front of the attribute you want to search.

a[title*="Contoso"]:hover:after{
content:" Contoso is a fictional Company";
}

Show Demo on JsFiddle

Attribute Value Start With Selector

Attribute Value Start With Selector is used to select all element which starts with the specific value.
For Example, a[title ^= “Contoso”] selects all the hyperlink which contain “Contoso” in the start of title attribute.
You Can specify Attribute Value Start With Selector by adding ^ (Caret Sign) in front of the attribute you want to search.

a[title^="Microsoft"]:hover:after{
content:" Microsoft is an American Company";
}

Show Demo on JsFiddle

Attribute Value End With Selector

Attribute Value End With Selector is used to select all element which end with the specific value.
For Example, a[title $= “Contoso”] selects all the hyperlink which contain “Contoso” in the end of title attribute.
You Can specify Attribute Value End With Selector by adding $ (Dollar Sign) in front of the attribute you want to search.

a[title$="Plus"]:hover:after{
content:" +";
}

Show Demo on JsFiddle

Advertisements

One thought on “CSS Selectors

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s