Wednesday, March 21, 2018

CSS Selectors - Level 3

In my previous blog post, we saw the selectors available in CSS 1 & 2. In this blog post, we shall continue our learning by looking at the new selectors in CSS 3.

New attribute selectors

CSS 3 introduces 3 new attribute selectors. These enable you to match elements based on substrings of the specified attribute's values. We'll take a look at each new selector below:

Type 1

The first attribute selector matches those elements whose attribute value begins with the string specified in the selector. Note that the selector is case-sensitive - it will match the element only if the value specified in the selector is the same case as the substring in the attribute.

The syntax of the selector is element[attribute^=value].

Here is an example. Consider the following HTML:
<div id="content-header">
    <span>CSS 2 is now a Recommendation</span>
</div>
<div id="content-gist">
    <span>The standards body has approved the various new features in CSS 2.</span>
</div>
<div id="content-body">
   <span>Detailed info on CSS 2 is found here.</span>
</div>
and the following CSS is applied to it:
div[id^=content] {font-style: italic;}
then the output we get is this:
What happened here is that because each div tag had its id attribute starting with 'content', all of its content was italicized.

Type 2

The second attribute selector matches those elements whose attribute value ends with the string specified in the selector. This selector is also case-sensitive.

The syntax of this selector is element[attribute$=value].

Here is an example. Consider the following HTML:
<div id="content-header">
    <span>CSS 2 is now a Recommendation</span>
</div>
<div id="content-gist">
    <span>The standards body has approved the various new features in CSS 2.</span>
</div>
<div id="content-body">
   <span>Detailed info on CSS 2 is found here.</span>
</div>
and the following CSS is applied to it:
div[id$=gist] {text-transform: uppercase;}
then the output we get is this:
The property rule matched only the second div tag since only its id attribute ended with 'gist'.

Type 3

The third attribute selector matches those elements whose attribute value contains the string specified in the selector. This selector is also case-sensitive.

The syntax of the selector is element[attribute*=value].

Here is an example. Consider the following HTML:
<div id="content-header">
    <span>CSS 2 is now a Recommendation</span>
</div>
<div id="content-gist">
    <span>The standards body has approved the various new features in CSS 2.</span>
</div>
<div id="content-body">
   <span>Detailed info on CSS 2 is found here.</span>
</div>
and the following CSS is applied to it:
div[id*=ten] {font-weight: bold;}
then the output we get is this:
What happened here is that because each div tag had its id attribute containing the 'ten' character sequence (due to the word 'content'), all of its content was made bold.

Structural pseudo-classes

CSS 3 introduces 11 new pseudo-classes for selecting elements based on their position in the document tree but which cannot be determined using the existing selectors.

Let's take a look at the first such pseudo-class, :nth-child, below. The remaining 10 pseudo-classes are similar with minor variations, & hence become easy to understand once you grok :nth-child. So, pay close attention.

:nth-child(an+b)

This selector is very powerful in selecting particular elements among multiple available elements. What this selector does is it splits all the elements into groups, and you can then specify individual elements inside those groups to target. Thus, you can build a powerful selector that targets specific elements.

The way this selector works is like this: you have to provide a formula of the form, an + b, when defining the selector, where a & b are integer values. Here, a represents a group of elements, and b represents the element inside the ath group. What the browser will then do is substitute values zero & above for n, and then evaluate the an+b expression. This will result in an integer that is the element for which the style is applied. For example, on substituting 0 for n, we get the first group, after which we can target the bth element in the group. Next, on substituting 1 for n, we get the second group, after which we can target the bth element in the group. This continues until all elements are exhausted.

This selector is useful in situations where multiple elements among a set of children have to applied the same style. Eg: alternating rows in a table need to be applied different background colours. In such cases, you'll have to construct the an+b formula in such a way that the required rows match.

The syntax of this selector is element:nth-child(an+b).

Consider this example HTML:
<tr>
    <th>Name</th>
    <th>Type</th>
    <th>Value</th>
</tr>
<tr>
    <td>Google</td>
    <td>W</td>
    <td>7</td>
</tr>
<tr>
    <td>DISH</td>
    <td>X</td>
    <td>26</td>
</tr>
<tr>
    <td>Jet</td>
    <td>Y</td>
    <td>34</td>
</tr>
<tr>
    <td>Yahoo!</td>
    <td>B</td>
    <td>7</td>
</tr>
We apply the below CSS to the HTML,
tr:nth-child(2n+3) {background-color:blue;}
and we get the following output:
What happened here is this: the browser started evaluating the formula by passing in values from 0 onwards to n. If we pass 0 to the formula, 2n + 3, then we get the value 3. Thus, you see the style applied to the 3rd row. If we pass 1 to the formula, then we get the value 5. Thus, you see the style applied to the 5th row. The browser will not evaluate further, since there are no more rows. Note here that because we gave the 'tr' tag in the selector, it included even the header row in its count.

This selector can be simplified further - for example, since the above CSS definition makes alternating rows to be a different background colour, you can change the definition to parent:nth-child(even) for even-numbered rows or parent:nth-child(odd) for odd-numbered rows.

As an example, if we change the CSS above to
tr:nth-child(odd) {background-color:blue;}
we get this:
Here we can see that the style has been applied to all odd rows. As mentioned before, since we used 'tr' in the selector, the count starts from the header row. Since the header row is the first row, it is an odd-numbered row, and hence the style is applied for that row.

As you can see from the above two examples, having an an+b formula in your selector is more powerful, since most of the times, we don't want the header row to be part of the alternate row colouring.

You can also remove certain operands of the formula if you're sure the values of a or b can only be zero. Eg: parent:nth-child(0n+2) can also be written as parent:nth-child(2).

Advantage of this selector

This selector has one other advantage which I haven't seen mentioned anywhere. Often, I have seen & written code like this in dynamically rendered pages:
<table>
    <% for each item in collection %>
        <% if row.counter % 2 != 0 %>
    <tr class = 'highlight'>
        <% else %>
    <tr>
        <% end %>
    content </tr>
    <% end %>
</table>
What's happening here is that we're checking to see if the row of the table we're rendering is an odd-numbered row. If yes, we add a CSS class to render that row in a background colour different from the even-numbered rows. If you see such code, you can replace them with this selector.

:nth-last-child(an+b)

This is similar to the :nth-child selector, except that it builds groups from the last element, rather than the first. Thus, after evaluating the an+b formula, you'll see that the browser's output is the reverse of nth-child.

The syntax of this selector is element:nth-last-child(an+b).

Consider the same HTML seen above:
<tr>
    <th>Name</th>
    <th>Type</th>
    <th>Value</th>
</tr>
<tr>
    <td>Google</td>
    <td>W</td>
    <td>7</td>
</tr>
<tr>
    <td>DISH</td>
    <td>X</td>
    <td>26</td>
</tr>
<tr>
    <td>Jet</td>
    <td>Y</td>
    <td>34</td>
</tr>
<tr>
    <td>Yahoo!</td>
    <td>B</td>
    <td>7</td>
</tr>
If we apply this CSS style,
tr:nth-last-child(2n+3) {background-color: blue;}
then we get the following output
What happened here is this: 2n+3 evaluates to 3 when n=0, and 5 when n=1. The browser counts rows from the bottom - the row with the Name field set to DISH is the 3rd row, and the header row becomes the 5th row. Hence, the styles are applied to those rows.

:nth-of-type(an+b)

This selector also follows the an+b format and selects an element which is the (an+b)th element among a set of elements. However, this selector will only select those elements of a specified type (aka HTML tag). Other elements not of the specified type will not be considered while applying the formula. This is useful when you know that other element types will be interspersed among the collection of elements that you are targeting.

The syntax of this selector is element:nth-of-type(an+b).

Consider the HTML:
<span>First span tag</span>
<span>Second span tag</span>
<div>First div tag</div>
<span>Third span tag</span>
<div>Second div tag</div>
<span>Fourth span tag</span>
If we apply this CSS style definition,
span:nth-of-type(2n+1) {color: blue;}
then we get the following output:
What happened here is this: 2n + 1 formula evaluates to 1 when n=0, and 3 when n=1. If we had used :nth-child instead of :nth-of-type, then the style would have been applied to the first span tag  & the first div tag. However, we have used :nth-of-type, which will apply the style only if they belong to the specified HTML type. In our case, that type is span. Hence, the style should be applied to the first & third span tags only, which is exactly what we see.

:nth-last-of-type(an+b)

This is similar to the :nth-of-type selector, except that it starts counting the children from the last child, rather than the first child. As stated in :nth-of-type, this selector does not count those children who are not of the specified type.

The syntax of this selector is element:nth-last-of-type(an+b).

Consider the same HTML seen above:
<span>First span tag</span>
<span>Second span tag</span>
<div>First div tag</div>
<span>Third span tag</span>
<div>Second div tag</div>
<span>Fourth span tag</span>
If we apply this CSS style definition,
span:nth-last-of-type(2n+1) {color: blue;}
then we get the following output:

:last-child

This selector simply selects the last child of the parent. (For those wondering if we have a corresponding :first-child selector, it was already introduced in CSS 2).

The way this selector works is like this: In the pseudo-class, you only specify the type of the element - no information about the parent is necessary. The pseudo-class searches for all elements of that type, and then runs through each result to determine if it is a child of some element, and if yes, if it is the last child. The result of this check gives a list of elements for which the style is applied.

The syntax of this selector is element:last-child. Note that this selector cannot have a formula, as it will not make sense - we only need to select the last child element & nothing else.

Consider the example HTML below:
<span>under the body tag</span> <div>
<span>First child under the div tag</span>
<span>Second child under the div tag</span> </div>
for which we apply the following CSS,
span:last-child {color:blue;}
Then the output we get is this:
What happened here is this: Of the 3 span tags, the first one didn't qualify because it had the div tag as a sibling following it - thus, it wasn't the last child for its parent. The first span tag inside the div tag also failed to qualify for the same reason. The second span tag inside the div qualified because it was a child, and it was the last child for its parent div tag.

:first-of-type

This selector selects those elements of a particular type, and which are a child of a parent and which are the first among the children of that type.

The syntax of this selector is element:first-of-type. Note that this selector cannot have a formula, as it will not make sense - we only need to select the first required element & nothing else.

Consider our usual example,
<tr>
    <th>Name</th>
    <th>Type</th>
    <th>Value</th>
</tr>
<tr>
    <td>Google</td>
    <td>W</td>
    <td>7</td>
</tr>
<tr>
    <td>DISH</td>
    <td>X</td>
    <td>26</td>
</tr>
<tr>
    <td>Jet</td>
    <td>Y</td>
    <td>34</td>
</tr>
<tr>
    <td>Yahoo!</td>
    <td>B</td>
    <td>7</td>
</tr>
If we apply the following CSS,
td:first-of-type {color: blue;}
then we get
What happened here is this: Of all available td tags, only the first td tag under each tr tag matched this selector. Hence, only those td tags got the style applied.

:last-of-type

This selector is similar to :first-of-type selector, but it selects the last element instead of the first.

The syntax of this selector is element:last-of-type. Note that this selector cannot have a formula, as it will not make sense - we only need to select the last required element & nothing else.

Consider our usual example,
<tr>
    <th>Name</th>
    <th>Type</th>
    <th>Value</th>
</tr>
<tr>
    <td>Google</td>
    <td>W</td>
    <td>7</td>
</tr>
<tr>
    <td>DISH</td>
    <td>X</td>
    <td>26</td>
</tr>
<tr>
    <td>Jet</td>
    <td>Y</td>
    <td>34</td>
</tr>
<tr>
    <td>Yahoo!</td>
    <td>B</td>
    <td>7</td>
</tr>
If we apply the following CSS,
td:last-of-type {color: blue;}
then we get

What happened here is this: Of all available td tags, only the last td tag under each tr tag matched this selector. Hence, only those td tags got the style applied.

:only-child

This selector selects only those elements that are children of an element, and are the only child for that element.

The syntax of this selector is element:only-childNote that this selector cannot have a formula, as it will not make sense - we only need to select a child element that does not have siblings.

Consider this example HTML,
<tr>
<th>Name</th>
<th>Type</th>
<th>Value</th>
</tr>
<tr>
<td>Google</td>
<td>W</td>
<td>7</td>
</tr>
<tr>
<td colspan=3>DISH</td>
</tr>
<tr>
<td>Jet</td>
<td>Y</td>
<td>34</td>
</tr>
When we apply the following CSS,
td:only-child {background-color: blue;}
we get,

:only-of-type

This selector selects only those elements that are children of an element, and are the only children of that type.

The syntax of this selector is element:only-of-typeNote that this selector cannot have a formula, as it will not make sense - we only need to select a child element that is of a unique type among its siblings.

Consider the below HTML,
<body>
<span>First span tag</span>
<span>Second span tag</span>
<div>First div tag</div>
<span>Third span tag</span>
<span>Fourth span tag</span>
</body>
When we apply the following CSS,
div:only-of-type {color: blue;}
we get,
What happened here is this: under the body tag, there is only one div tag. This means that it matches the definition of the :only-of-type pseudo-class which states that there must be only one child of that type for its parent. Thus, the style is applied to that single div tag.

What happens if we add one more div tag? The HTML becomes:
<body>
<span>First span tag</span>
<span>Second span tag</span>
<div>First div tag</div>
<div>Second div tag</div>
<span>Third span tag</span>
<span>Fourth span tag</span>
</body>
and the output becomes
Here the style was not applied, because the two div tags did not satisfy the condition of there being only one element of that type.

:empty

The empty selector selects those elements that do not have any children.

The syntax of this selector is element:emptyNote that this selector cannot have a formula, as it will not make sense - it only needs to select empty elements.

Consider this example HTML,
<div></div>
<div>First span</div>
and this CSS that we apply to the HTML,
div:empty:before {content: "empty";}
Then we get this output:
What happened here is: The first div tag matched the selector since it was an empty element. The selector definition says that the word, "empty" must be added to the empty div, which is what we see.

UI element state pseudo-classes

CSS 3 provides 3 pseudo-classes that let you select elements based on the current UI state of the element. The states supported are: :enabled, :disabled & :checked. The last one obviously is only for checkboxes & radiobuttons.

:enabled & :disabled

The :enabled & :disabled pseudo-classes enable us to write selectors that match those elements which are enabled (or) disabled respectively. Thus, we can apply different styles to elements based on the UI state of the element.

The syntax of this selector is element:enabled or element:disabled.

Consider the following HTML that has two buttons,
<input type=button value="Button 1"/>
<input type=button value="Button 2" disabled />
When the following CSS is applied to it,
input:enabled {color:red;}
input:disabled {color:blue;}
then we get

:checked

This pseudo-class enables developers to assign styles if the particular checkbox or radiobutton is checked.

The syntax of this selector is element:checked.

Consider the following HTML,
<input type=checkbox value="1" id="name"/>
<label for="name">Travelling alone?</label>
to which we apply the following CSS,
input:checked + label {color: green;}
We get the following output:
When unchecked,


When checked,


Negation pseudo-class

Till now, most selectors that you saw matched elements if they met the conditions the selectors imposed. CSS 3 introduces a new selector which selects those elements if they do not meet a particular condition.

Consider the following HTML,
<div>First div</div>
<span>First span</span>
<span>Second span</span>
<div>Second div</div>
to which we apply the following CSS,
body *:not(span) {color: blue;}
on which we get the following output:
What happened here? The selector looked for those elements that were not span tags, and then applied the styling only to those.

The :target pseudo-class

Some URLs have a fragment identifier so that the user agent can load the URL and then move the viewport to the relevant section of the page. In such cases, it may be necessary to apply special styling to highlight the particular portion of the page. The :target pseudo-class can be used for this purpose.

The syntax of this selector is element:target.

Let's consider this crazy example HTML that I just made up:
<div>
    <div>div 1</div>
    <div>div 2</div>
    <div>div 3</div>
    <div>div 4</div>
    <div>div 5</div>
    <div>div 6</div>
    <div>div 7</div>
    <div>div 8</div>
    <div>div 9</div>
    <div>div 10</div>
</div>
<div>
    <div>div 11</div>
    <div>div 12</div>
    <div>div 13</div>
    <div>div 14</div>
    <div>div 15</div>
    <div>div 16</div>
    <div>div 17</div>
    <div>div 18</div>
    <div>div 19</div>
    <div>div 20</div>
</div>
<div>
    <div>div 21</div>
    <div>div 22</div>
    <div>div 23</div>
    <div>div 24</div>
    <div>div 25</div>
    <div>div 26</div>
    <div>div 27</div>
    <div>div 28</div>
    <div>div 29</div>
    <div>div 30</div>
</div>
<div>
    <div>div 31</div>
    <div>div 32</div>
    <div>div 33</div>
    <div>div 34</div>
    <div>div 35</div>
    <div>div 36</div>
    <div>div 37</div>
    <div>div 38</div>
    <div>div 39</div>
    <div>div 40</div>
</div>
<div id=bottom_div>
    <div>div 41</div>
    <div>div 42</div>
    <div>div 43</div>
    <div>div 44</div>
    <div>div 45</div>
    <div>div 46</div>
    <div>div 47</div>
    <div>div 48</div>
    <div>div 49</div>
    <div>div 50</div>
</div>

Now the reason I have so many div tags with dummy content inside them is so that when I load the page, I get a scrollbar, and some content is below the fold, as seen below:

Let's say I want the browser to load the page & directly scroll to some content that I want the user to focus on. HTML has the concept of fragment identifiers to achieve this. Fragment identifiers are those parts of the URL that begin after the URL with a '#' symbol, and which represent an HTML element's ID.

Let's apply this to our document. For doing so, we need a div tag with an ID. Notice that div tags with numbers 41-50 are wrapped in a special div tag with id, 'bottom_div'. You can use this id in the URL to make that ID come up in the browser's viewport, even if it normally would have been below the fold. Thus, on your browser, enter '#bottom_div' at the end of the URL. You will get the page like this:
Now assume we apply the following CSS to the HTML:
#bottom_div:target {color:red;}

Then on refreshing the page with the fragment identifier in the URL, we will get this:

What happened here? When loading the page with the fragment identifier, the browser automatically moved the viewport to that fragment, and the CSS selector applied the styling to highlight that portion. If the same page had not been loaded with the fragment identifier, then the styling would not have been applied even if the style definition existed in the CSS file.

Preceding sibling selector

This selector is used to select those elements which are preceded by certain specified elements.

The syntax of this selector is preceding_sibling ~ targeted_element.

Consider the following HTML,
<div>
<ul>
<li>
<span>This is the first list item.</span>
</li>
</ul>
</div>
<span>First span under div</span>
<span>Second span under div</span>
to which we apply the following CSS:
div~span {color:blue;}
In that case, we get the following output
What happened here is that the browser looked for span tags that appeared immediately after div tags. Only those span tags that matched this condition were applied the style. Thus, the last two span tags got the style, while the span tag inside the div did not.

Wednesday, September 20, 2017

CSS Selectors - Level 1 & 2

As my interest in CSS grew, I have come across more CSS selectors that I should have used in my projects, but haven't due to ignorance. I wrote this blog post more as a way to freeze these selectors in my brain so that I remember to use them next time. To keep things simple, I make two assumptions for this post:
  1. We're trying to use CSS for HTML, and
  2. We're only using CSS selectors until CSS Selectors level 3. Level 4 is not yet a W3C Recommendation, so when that happens, I shall have a new blog post.
Also, this blog post talks only about selectors in CSS 1 & 2. Selectors in CSS 3 will be looked at in another blog post.

Level 1 CSS selectors


When CSS was first announced, it was called Level 1 CSS. It had only a few selectors. (Later "versions" of CSS added more selectors, as demands from web designers grew.) Because CSS 1 is quite old, it's also extremely well-known among developers & designers. Thus, for the most popular selectors in CSS 1, I'll skim over them as most developers/designers know these by now.

Type selector

This selector only contains the name of an HTML tag. All elements on the page of that type will be applied the associated style.
An example: span {color:red}

This will make all text inside <span> tags red in colour.

ID selector

The ID selector contains the name of an HTML element's ID attribute. Only the element that has that particular value for the ID attribute will have the style applied to it. The ID selector is constructed by having the hash (#) symbol followed by the HTML element's ID without any space.

Eg: #content {color:red} will render the HTML element with ID 'content' in red coloured text.

Class selector

The class selector defines a style that can be applied to a class (aka. category) of HTML elements. What determines if an element belongs to the class or not is the class attribute of the HTML element. If the class attribute's value matches the class selector, then the style is applied.

As an example, consider two span tags,
<span id="span1">Content</span>
<span id="span2" class="important_content">Warning message</span>

and a style definition,
.important_content {color: red;}

In the above case, only the <span> tag with id 'span2' will have the content in red colour. This is because it is the only <span> tag that belongs to the class of elements represented by 'important_content'. Other <span> tags in the same document do not belong to that class of elements and hence will not have the content in red colour.

Because this selector is used to categorize elements into a single grouping, you can have multiple elements having the same value for the class attribute - all those elements will be grouped into a single category represented by that class selector, and the style will be applied for all those elements.

Descendant selector

The descendant selector is used to select any element that is a descendant of any other element.

The syntax is ancestor targeted_element. The style is applied to targeted_element.

Here is an example. Consider you have the following HTML:
<div>
    <span>Span tag inside a div tag</span>
    <ul>
        <li>
            <span>This is the first list item.</span>
        </li>
        <li> This is the second list item.</li>
    </ul>
</div>
with this CSS applied:
div span {color:blue;}
The output we get is:

What's happening here is that all <span> tags at all levels of the <div>'s subtree get the style applied.

Pseudo-classes

CSS 1 had 3 pseudo-classes: :link, :visited, and :active. These work only on links and therefore, defining them on other elements has no effect. The :link pseudo-class is to specify how links will normally be shown, the :visited pseudo-class is to specify how those links on the page which point to URLs you have already visited are to be shown, and the :active pseudo-class is to specify how a link should appear when it is currently being selected.

Pseudo-elements

CSS 1 had 2 pseudo-elements: :first-letter & :first-line.
Note that in CSS 3, the single colon (:) at the beginning of each pseudo-element has been replaced by the double colon (::). Thus, if you're trying out these examples on a modern browser, remember to use double colons.For convenience, my example code already has them replaced.

The :first-letter pseudo-element

The :first-letter pseudo-element is used to specify a styling only for the first-letter of the element's content. Sometimes, it is to indicate that a new paragraph has started; other times it is for publishing scenarios such as drop caps.
As an example, let us assume that you have the following HTML content:
<div id=first_div>
    This is a single line of text.
</div>
<div id=second_div>76 is a number.</div>
<div id=third_div>
    "Let's go", he said, with determination.
</div>
and the following CSS is applied to the HTML:
#first_div::first-letter {font-size: 20pt;}
#second_div::first-letter {font-size: 20pt;}
#third_div::first-letter {font-size: 20pt;}
The result is this:
What's happening here is that the first letter of each <div> tag is being applied the style to increase its font size. We are able to do this without wrapping the first letter in any special tag (eg: a <span> tag). If not for the :first-letter pseudo-element, wrapping the first letter in a special tag would be the only way to achieve the same effect.

This is also the reason why :first-letter is a pseudo-element. The CSS selector applies the style as if there was a tag wrapped around the first letter with that special styling.

What is also noticeable is that if the content of the element starts with any quotes, then the :first-letter style applies to the quotes and the letter following it.

The :first-line pseudo-element

The :first-line pseudo-element is used to specify a styling only for the first line of the element's content. This is often required in publishing scenarios where publishers may prefer to highlight the first line of a new paragraph to make it easier to identify that a new paragraph is starting here.
As an example, let us assume that you have the following HTML content:
<div>
    They walked into the forest, not entirely unmindful of the animals that lurked there. But to them, much more than the dangers the animals represented, was the fear of losing out - of not achieving their goal.
</div>
and the following CSS is applied to the HTML:
div::first-line {text-transform:uppercase;}
The result is this:
What happened here is that only the first line of the <div> tag is in upper-case. Notice that we mean first line & not first sentence, i.e., CSS does not look for a full-stop (aka period) to indicate the end of the first sentence. It only applies the style until the content in the <div> tag wraps to the next line, at which point the style application stops.

If you resize your browser window to make the line longer or shorter, more (or less) content will be made upper-case.

Level 2 CSS selectors

Let us now look at what was newly introduced in CSS 2.

Universal selector

The universal selector represents all elements in an HTML document. The universal selector can only be written using the asterisk (*) symbol.
An example: *{color:red}
This will make all text red in colour.

Attribute selectors

CSS 2 introduces the concept of attribute selectors, where you can specify that your styles must match only those elements that have certain attributes or characteristics of attributes. CSS 2 introduces 4 attribute selectors (CSS 3 adds 3 more). Let's take a look at the 4 attribute selectors below:

Presence selector

This selector matches those elements that have the attribute specified. The attribute only has to be present in the element - it can have any value or it can have no value.

The syntax of the selector is element[attribute].

As before, here's an example. Let's assume you have the following HTML code:
<div id=first_para>
    <span>This is the first paragraph.</span>
</div>
<div id=second_para>
    <span>And this is the second.</span>
</div>
and the following CSS:
div[id] {color:blue;}
The result is this:
What happened here is that the blue colour styling was applied to both <div> tags, even though they have different HTML IDs. That is because the selector only checks for the presence of the attribute - it doesn't check for the presence of a value.

Where would such selectors be used? In HTML, there are places where an attribute just has to exist for some behaviour to be triggered - the attribute doesn't have values as per the HTML spec. An example is the selected attribute for checkboxes & list boxes.

Value selector

This selector matches those elements that have the attribute specified, and that attribute's value is the value specified in the selector. Note that this selector is case-sensitive - it will match the element only if the value of the attribute is the same case as the one specified in the selector.

The syntax of the selector is element[attribute=value].

Let's assume you have the following HTML:
<div id=first_para>
    <span>This is the first paragraph.</span>
</div>
<div id=First_para>
    <span>This is the second paragraph, but has the same ID, different only in case.</span>
</div>
and this CSS:
div[id=first_para] {color:blue;}
The output we get is this:
What happened here is that only the <div> tag with the ID attribute having first_para as its value got the style applied. Other <div> tags did not get that style because they didn't have the exact value with the exact case as in the selector.

Attribute sub-string selectors

There are 2 attribute selectors available in CSS 2.

The first selector matches those elements that have the attribute specified, and that attribute's value is the value specified in the selector. However, this selector will also match if the attribute has multiple values separated by spaces, and one of those values is the value specified in the selector.

The syntax of the selector is element[attribute~=value].

Here's an example. Assume that you have the following HTML:
<div id="content header">
    <span>CSS 2 is now a Recommendation</span>
</div>
<div id="content gist">
    <span>The standards body has approved the various new features in CSS 2.</span>
</div>
<div id="content body">
    <span>Detailed info on CSS 2 is found here.</span>
</div>
and the following CSS
div[id~=header] {text-transform:uppercase;}
div[id~=gist] {font-style: italic;}
the output will be:
The first property rule matched the first <div> tag because the id attribute has the word, header, in it. Similarly, the second property rule matched the second <div> tag because the id attribute has the word, gist, in it.
Again, as in previous selectors, the selector matches only if the attribute matches case-sensitively.

The second attribute sub-string selector matches those elements that have the attribute specified, and that attribute's value is the value specified in the selector. However, this selector will also match if the attribute has multiple values separated by hyphens, and that hyphenated set of values starts with the value specified in the selector.

The syntax of the selector is element[attribute|=value].

Let's look at an example. Assume the following HTML:
<div id="header-content">
    <span>CSS 2 is now a Recommendation</span>
</div>
<div id="gist-content">
    <span>The standards body has approved the various new features in CSS 2.</span>
</div>
<div id="body-content">
    <span>Detailed info on CSS 2 is found here.</span>
</div>
and the CSS applied is:
div[id|=header] {text-transform:uppercase;}
div[id|=gist] {font-style: italic;}
then the output we get is:
As before, the first property rule matched the first <div> tag, and the second property rule matched the second <div> tag.
Again, the attribute value is matched case-sensitively.

Child selectors

CSS 2 introduces the concept of child selectors, where you can specify which children of an element should your selector match. Note that this is different from the descendant selectors we saw in the CSS 1 section - the child selectors in CSS 2 only select children, while the descendant selector can go deeper in the tree.

CSS 2 introduces 2 child selectors, while CSS 3 introduces a lot more. Let's take a look at the 2 CSS 2 child selectors below:

:first-child pseudo-class

The :first-child pseudo-class matches those elements which are the first child of a parent element. In the pseudo-class, you only specify the type of the child element - no information about the parent needs to be provided. The pseudo-class searches for all elements of that type, and then runs through each result to check if it is a child of some other element, and if yes, checks further to determine if it is the first child. The result of this check gives a list of elements for which the style is applied.

The syntax is child-element:first-child.

Consider this example HTML:
<span>under the body tag</span><div>
    <span>First child under the div tag</span>
    <span>Second child under the div tag</span>
</div>
</body>
and this CSS that is applied on that HTML:
span:first-child {color:blue;}
the output we get is:
What happened here is that all tags inside the <body> tag are children of the <body> tag. Thus, the <span> tag immediately following the <body> tag is treated as a child, and it is the first child of the <body> tag. Thus the styling applied to it.

For the <span> tags inside the <div> tag, the first <span> tag is the first child of the <div> & hence got the styling applied, while the second <span> did not.

Again, the advantage here is that we got this styling applied without the need for any special elements to wrap around the first child. Also, in cases of DHTML, the browser will take care of applying the style in case children are added/removed.

Generic child selector

Another child selector available is the more generic version of the :first-child pseudo-class. It is used to match any element that is a child of any other element. This selector allows you to specify even the parent element of the targeted child element.

The syntax is parent > child.

Assume the following HTML:
<div>
    <span>first span</span>
    <span>second span</span>
    <ul>
        <li>
            <span>This is the first list item.</span>
        </li>
        <li> This is the second list item.</li>
    </ul>
</div>
and the following CSS:
div>span {color:blue;}
the output we get is:
The first two <span> tags under the <div> tag are matched. This is because the selector matches all children, not just the first child.

The <span> tags inside the <ul> tags are not matched because the selector only matches children of the parent, not grandchildren & other descendants.

Adjacent sibling selectors

CSS 2 also introduces the concept of sibling element selectors. The sibling selector is used to select those elements which have a specified sibling element that appears before them. Note that the specified sibling must appear before & not after.

The syntax for this selector is sibling + targeted_element. The style will be applied to targeted_element.

Consider this HTML:
<div>
    <ul>
        <li>
            <span>This is the first list item.</span>
        </li>
    </ul>
</div>
<span>First span under div</span>
<span>Second span under div</span>
and this CSS:
div+span {color:blue;}
then the output is:
What's happening here is that the first <span> tag has the style applied because its siblings is the <div> tags specified in the selector, and that <div> tag appears before the <span> tag.

Also, the <span> tags inside the <ul> tag are not selected by the selector since they do not have any siblings. Similar, the final <span> tag is also not selected since it's immediate preceding sibling is another <span> tag.

New pseudo-elements

CSS 2 introduces 2 new pseudo-elements, ::before & ::after. These pseudo-elements are used to render content either before or after the element. What's the big deal, you may ask? The deal is this: Sometimes you have a need to render repeating content, and the repeating content may need to appear either before or after a set of elements. An example of such a usecase would be adding red asterisks after every label in a form to indicate required fields. Instead of writing it into the HTML, you can style it as a CSS rule.

Assume we have the following form:
<form>
    <label for=id_no class=required>Identification Number</label>
    <input type=text name=id_no />
    <br>
    <label for=name>Name</label>
    <input type=text name=name />
    <br>
    <input type=submit />
</form>
with this CSS:
.required::after
{
    content: "*";
    color: red;
}
It results in this output:

Examples of other repeating content are page numbers, chapter numbers, etc.
Note that in CSS 3, the single colon (:) at the beginning of each pseudo-element has been replaced by the double colon (::). Thus, if you're trying out these examples on a modern browser, remember to use double colons.For convenience, my example code already has them replaced.

New pseudo-classes

The :lang pseudo-class

CSS 2 introduces a new pseudo-element, :lang. This pseudo-element is used to set styles based on the language of the document. The language may be set by multiple mechanisms depending upon the markup language, but in HTML, it is usually set using the lang attribute on the <html> tag.

Consider the HTML:
<html lang="fr">
    <head>
        <title>E:lang</title>
        <link href="lang.css" rel=stylesheet />
    </head>
    <body>
        <div>some content</div>
    </body>
</html>
and the content in lang.css:
div:lang(fr) {color:blue;}
then the output is that the text is rendered in blue colour.

If the language was changed to English("en") in the HTML, but not in the CSS file, then the text will be rendered in the browser's default colour.

The :hover & :focus pseudo-classes

The :hover pseudo-class is used to apply styling when the mouse pointer is currently over the element. The :focus pseudo-class is used to apply styling when the element receives focus, which can be due to mouse-click or a keyboard event.

As an example, consider the following HTML:
<input type=submit />
with the following CSS applied:
input:hover {cursor: pointer;}
input:focus {color: blue; border: 2px black solid;}
The following output is obtained when we press the Tab key to move focus to the button:

 You will also notice that if you move the mouse over the button, the mouse pointer will become the hand pointer instead of the typical arrow pointer.

Thursday, June 08, 2017

[CSS] How are conflicting styles resolved?

If you have worked in CSS, then you’ll know that you can assign a CSS property using the syntax:
property-name: value
For example, if you have a <span> tag with ID ‘content’, for which you want to assign the color green, you’d add this in your CSS file:
#content { color: green; }
There are other ways you can specify the same property:
span#content {color: green;}, and
.content {color: green;} in combination with <span class="content">lorem ipsum</span>

Here's the interview question

What happens though when you have multiple instances of the same property being set & they all apply to the same HTML tag too? Here’s an example:
Consider this tag,
<span id="content" style="color: blue;">some content</span>
while the CSS definition in the associated CSS file that can match the element is:
#content {color: green;}
Since multiple styles match, which one will the browser render? Answer: The text in the span element will be rendered in blue.
Why? Why did the browser decide to apply blue? As per the CSS spec, there are two aspects to be considered when deciding which style a browser will apply among competing styles. Resolving these two aspects tells the browser which competing style should win. They are: 1) Cascading order, & 2) Specificity. We'll first look at Cascading order and later in the post, Specificity.

Cascading order

In English, the term "cascade" is used to describe a process where there are multiple steps. For example, a cascading waterfall is one in which water flows down multiple steps.
If that is the case, what does "Cascading Style Sheets" mean? What steps are there in CSS? It turns out there are multiple ways through which style definitions for a web page can be assigned. They are: author, user & user agent.
  • Author styles are those which all software developers know - they are created by the authors of the web page as CSS files or style attributes in HTML tags.
  • User styles are those styles which users of web browsers can configure on their browser. For example, users can configure that browsers render particular fonts by replacing it with other fonts - this is particular useful from an accessibility standpoint.
  • User agent styles are those styles that are provided by default by the browser. For example, if no colour information is provided, then text is rendered black on a white background by default - this is an example of user agent styling.
The "cascade" in Cascading Style Sheets flows thus: If there are conflicts in property definitions across user, author or user agent style definitions, then the precedence is as follows:
Author > User > User agent

Example 1

In this example, we’re going to determine what happens if a user CSS file has a definition that conflicts with a definition in the user agent's default CSS file. The user agent we’re going to use is Internet Explorer. It already has a user agent CSS file (this is why a plain HTML file without any styling will render black text on a white background.) We will now change the way IE renders text color inside tags by default by providing a user CSS file.
Create a file by name, my_style.css. The content of this file is just this one line:
div{color:red}
We will now tell IE to use this file from now on for all web pages. The way to do so is this:
  • Open Internet Explorer
  • Click on the Tools menu & choose Internet Options
  • Click on the General tab & choose Accessibility. You should get a screen like this:
  • Under the User style sheet section, enable the Format documents using my style sheet checkbox.
  • Now click Browse… under the same checkbox and choose my_style.css.
  • Restart Internet Explorer.
We now need to create an HTML file that we can load into the browser to test that IE uses the my_style.css. Create a file by name, test_my_style.html. The content of this file is:
<html>
  <head>
     <title>Testing user styles</title>
  </head>
  <body>
      <div>This is a test file to test user styles.</div>
  </body>
</html>
Opening this file in Internet Explorer gives us this output:
What happened here? The user agent, by default, will render text inside tags as black-colored text. Our user file, my_style.css, overrode that, thus creating a conflict. IE followed the CSS spec which states that User CSS property definitions have priority over user agent CSS property definitions and rendered the text in red color.

Example 2

What happens if we introduce a further conflict by having an author-defined CSS file? For this, we will create another CSS file, author_style.css, where we will provide the following definition:
div {color:blue}
We will also change test_my_style.html to include author_style.css as follows.
<html>
  <head>
    <title>Testing user styles</title>
    <link href="author_style.css" rel="stylesheet"></link>
  </head>
  <body>
    <div>This is a test file to test user styles.</div>
  </body>
</html>
Opening this file in Internet Explorer gives us this output:
What happened here? The user agent, by default, will render text inside tags as black-colored text. Our user file, my_style.css, overrode that, thus creating a conflict. The author’s CSS file, author_style.css, overrode that even further setting up another conflict. IE followed the CSS spec which states that Author CSS property definitions have priority over all other CSS property definitions and rendered the text in blue color.

An exception

The only exception to the cascade order above is if the property definition is marked as !important, in which case that definitions take precedence over other definitions for that property. There are no property definitions marked !important in the user agent CSS file.
Let’s look at an example: We will reuse the same files as before, but we will change my_style.css to this:
div{color:red !important}
Now if we open our test_my_style.html in IE, we get this output:
What happened here? The user agent, by default, will render text inside tags as black-colored text. Our user file, my_style.css, overrode that, thus creating a conflict. The author’s CSS file, author_style.css, overrode that even further setting up another conflict. However, IE noticed the !important in my_style.css and followed the CSS spec which states that User CSS property definitions with !important have priority over all other CSS property definitions and rendered the text in red color.

Specificity

The approach mentioned above will still cause conflicts since one of the user/author stylesheets can have conflicting style definitions. To resolve this, CSS provides another mechanism which browsers can use - specificity. While there isn’t a definition of specificity in the spec, my definition is: Specificity determines how specific the style definition is. Here, specific means how many HTML elements does the CSS selector match - the less elements it matches, the more specific it is, the more elements it matches, the less specific it is.

Calculation of specificity

The calculation of specificity is done in the following manner:
Assume there are four numbers separated by commas, and their initial values are zero:
0,0,0,0
The first number represents the presence of a style attribute in the element's HTML. If a style attribute is present, then the first number becomes 1, otherwise 0.
The second number represents the number of id attributes in the selector.
The third number represents the number of attributes and pseudo-classes in the selector.
The fourth number represents the number of element names and pseudo-elements in the selector.
Unlike in the decimal system, if a number reaches the value 10, then it does not carry over to the preceding number. Thus, specificity values like 0,10,0,9 are perfectly valid.
Now that we know what specificity is, let’s take a look at some example CSS definitions, and try to understand what specificity value they evaluate to:
Example 1: div.content {color:red}. It is not a style attribute in a HTML tag, nor does it have any HTML IDs mentioned in the selector. Thus the first two numbers are 0,0. It has a class attribute value mentioned(.content), and it also has a HTML element mentioned (div). Thus, the final two values of the specificity are 1,1. Hence it's final specificity value is 0,0,1,1.
Example 2: #content::first-letter. It is not a style attribute in a HTML tag, but it has a HTML ID mentioned in the selector. Thus the first two numbers are 0,1. It has a pseudo-element mentioned(::first-letter), and it doesn't have any HTML elements mentioned. Thus, the final two values of the specificity are 0,1. Hence it’s specificity value is 0,1,0,1.
Example 3: div[data-name=Tom][data-url=/member/1]. It is not a style attribute in a HTML tag, nor does it have any HTML IDs mentioned in the selector. Thus the first two numbers are 0,0. It has two attributes mentioned(data-name & data-url), and it has 1 HTML element mentioned (div). Thus, the final two values of the specificity are 2,1. Hence it’s specificity value is 0,0,2,1.

Resolving conflicts with specificity

Given two specificity values, you can compare them to find out which one is greater or lesser. A specificity value is greater than another specificity value if the first specificity’s first number is greater than the second specificity’s first number. In case the first number of both values are the same, then the browser moves on to compare the second number of both specificity values, and so on.
Here are some examples:
1,0,0,0 is greater than 0,10,0,0
0,10,0,0 is greater than 0,0,20,0
How is specificity helpful in resolving conflicts? As per the CSS spec, browsers are supposed to resolve conflicts by choosing those CSS definitions that have a higher specificity.

Example

Let’s take the example in the interview question above:
In the HTML, we have:
<span id="content" style="color: blue;">some content</span>
while in the CSS file, we have:
#content {color: green;}
Constructing the specificity for the style definition in the HTML style attribute, we get:
1,0,0,0
Constructing the specificity for the CSS style definition, we get:
0,1,0,0
Because the first specificity value is greater than the second, the style definition in the style attribute of the HTML tag wins.

Is it possible to still have conflicts?

Yes. For example, there could be two definitions in an author CSS file which target the same elements and have the same specificity. In such cases, the CSS spec says that browsers can use the definition that appears later.
An example:
Let’s say that we have two CSS definitions as below:
div {color:blue};
div {color:red};
for this HTML,
<html>
  <head>
     <title>Testing user styles</title>
  </head>
  <body>
     <div>This is a test file to test user styles.</div>
  </body>
</html>
Both CSS definitions evaluate to a value of 0,0,0,1.
In this case, the browser will simply render the text in red.