CSS – Specificity & Inheritance & Cascade

When the same element is selected by two or more rules, specificity is used to determine which rule wins out. A selector’s specificity is determined by the components of the selector itself. A specificity value is expressed in four parts, like this: 0,0,0,0. The actual specificity of a selector is determined as follows:

  • For every ID attribute value given in the selector, add 0,1,0,0.
  • For every class attribute value, attribute selection, or pseudo-class given in the selection, add 0,0,1,0.
  • For every element and pseudo-element given in the selector, add 0,0,0,1.
  • Combinators and the universal selector do not contribute anything to the specificity.
    Universal selector has a specificity of 0, 0, 0, 0
    Combinators have no specificity at all, not even zero.

Examples:
h1 {color: red;} /* specificity = 0,0,0,1 */
p em {color: purple;} /* specificity = 0,0,0,2 */
.grape {color: purple;} /* specificity = 0,0,1,0 */
*.bright {color: yellow;} /* specificity = 0,0,1,0 */
p.bright em.dark {color: maroon;} /* specificity = 0,0,2,2 */
#id216 {color: blue;} /* specificity = 0,1,0,0 */
div#sidebar *[href] {color: silver;} /* specificity = 0,1,1,1 */

h1 {color: red;} /* 0,0,0,1 */
body h1 {color: green;} /* 0,0,0,2 (winner)*/

h2.grape {color: purple;} /* 0,0,1,1 (winner) */
h2 {color: silver;} /* 0,0,0,1 */

html > body table tr[id="totals"] td ul > li {color: maroon;} /* 0,0,1,7 */
li#answer {color: navy;} /* 0,1,0,1 (winner) */

  • Specificity is sorted from left to right. A specificity of 1, 0, 0, 0 will win out over any specificity that begins with a 0, no matter what the rest of the numbers might be.
  • Every inline style declaration has a specificity of 1, 0, 0, 0
  • Important declarations:
    p.dark {color: #333 !important; background: white !important;}
    Declarations that are marked !important do not have a special specificity value, but are instead considered separately from nonimportant declarations. In effect, all !important declarations are grouped together, and specificity conflicts are resolved relative to each other. Similarly, all nonimportant declarations are considered together, with property conflicts resolved using specificity. In any case where an important and a nonimportant declaration conflict, the important declaration always wins.

=====================================================================================

Inheritance is the mechanism by which styles are applied not only to a specified element, but also to its descendants.

Inherited values have no specificity at all, not even zero specificity.
Example:
* {color: gray;}
h1#page-title {color: black;}

<h1 id=”page-title”>Meerkat <em>Central</em></h1>
<p>
Welcome to the best place on the web for meerkat information!
</p>

In this example, the word “central” will be gray because zero specificity defeats no specificity.

======================================================================================

Cascade rules for CSS:

  1. Find all rules that contain a selector that matches a given element.
  2. Sort by explicit weight all declarations applying to the element. Those rules marked !important are given higher weight than those that are not. Sort by origin all declarations applying to a given element. There are three origins: author, reader, and user agent. Under normal circumstances, the author’s styles win out over the reader’s styles. !important reader styles are stronger than any other styles, including !important author styles. Both author and reader styles override the user agent’s default styles.
  3. Sort by specificity all declarations applying to a given element. Those elements with a higher specificity have more weight than those with lower specificity.
  4. Sort by order all declarations applying to a given element. The later a declaration appears in the style sheet or document, the more weight it is given. Declarations that appear in an imported style sheet are considered to come before all declarations within the style sheet that imports them.

There are five levels to consider in terms of declaration weight (from the origin of the rule). In order of most to least weight, these are:

  1. Reader important declarations
  2. Author important declarations
  3. Author normal declarations
  4. Reader normal declarations
  5. User agent declarations

CSS Selectors

Each CSS rule has 2 fundamental parts – the selector and the declaration block.
Example: h1 {color: red; background: yellow;} – h1 is the selector, and {…} is the declarations.

A value is either a single keyword or a space-separated list of one or more keywords that was permitted for that property.
Example: p {font: medium Helvetica;}

If you use either an incorrect property or value in a declaration, the whole thing will be ignored.

CSS keywords are separated by spaces except in one instance. In the CSS property font, there is exactly one place where a forward slash (/) can be used to separate two specific keywords.
Example: h2 {font: large/150% sans-serif;}

=================================================================================================

1. Universal selector

An asterisk (*). This selector matches any element at all.
Example: * {color: red;}

=================================================================================================

2. Grouping selectors and declarations

h1, h2, h3, h4, h5, h6 {color: gray; background: white; padding: 0.5em; border: 1px solid black; font-family: Charcoal, sans-serif;}

=================================================================================================

3. Class selectors

.warning {font-style: italic;}
span.warning {font-weight: bold;}

In HTML, it’s possible to have a space-separated list of words in a single class value.
<p class=”urgent warning”>Hello</p>
The order of the words doesn’t actually matter; warning urgent would also suffice.

Say you want all elements with a class of warning to be boldface, those with a class of urgent to be italic, and those elements with both values to have a silver background. This would be written as follows:
.warning {font-weight: bold;}
.urgent {font-style: italic;}
.warning.urgent {background: silver;}

By chaining two class selectors together, you can select only those elements that have both class names, in any order.
If a multiple class selector contains a name that is not in the space-separated list, then the match will fail. Consider the following rule:
p.warning.help {background: red;}
The selector will match only those p elements with a class containing the words warning and help. Therefore, it will not match a p element with just the words warning and urgent in its class attribute. It would, however, match the following:
<p class=”urgent warning help”>Help me!</p>

Note: class and ID are case-sensitive in HTML.

=================================================================================================

4. ID selectors:

#first-para {font-weight: bold;}
This rule applies boldface text to any element whose id attribute has a value of frist-para.
Between class selector and ID selector, IDs carry more weight when you’re trying to determine which styles should be applied to a given element.

=================================================================================================

5. Attribute Selectors:

planet[moons] {font-weight: bold;}
*[title] {font-weight: bold;}
a[href][title] {font-weight: bold;}
planet[moons="1"] {font-weight: bold;}
a[href="http://www.w3.org/"][title="W3C Home"] {font-size: 200%;}

Note:
ID selectors and attribute selectors that target the id attribute are not precisely the same. In other words, there is a subtle but crucial difference between h1#page-title and h1[id="page-title"]. The Specificity is different. ID selectors have a higher specificity (more important) than attribute selectors.

  • Selection based on partial attribute values:
    p[class~="warning"] {font-weight: bold;}
    img[title~="Figure"] {border: 1px solid gray;}
  • [foo^="bar"]
    Selects any element with an attribute foo whose value begins with “bar”.
  • [foo$="bar"]
    Selects any element with an attribute foo whose value ends with “bar”.
  • [foo*="bar"]
    Selects any element with an attribute foo whose value contains the substring “bar”.
  • The particular attribute selector:
    *[lang|="en"] {color: white;}
    This rule will select any element whose lang attribute is equal to en or begins with en-. Therefore, the first three elements below markup would be selected, but the last two would not:
    <h1 lang=”en”>Hello!</h1>
    <p lang=”en-us”>Greetings!</p>
    <div lang=”en-au”>G’day!</div>
    <p lang=”fr”>Bonjour!</p>
    <h4 lang=”cy-en”>Jrooana!</h4>
    In general, the form [att|="val"] can be used for any attribute and its values. Say you have a series of figures in an HTML document, each of which has a filename like figure-1.gif and figure-3.jpg. You can match all of these images using the following selector:
    img[src|="figure"] {border: 1px solid gray;}

=================================================================================================

6. Descendant selector (contextual selector)

Style only those em elements that are descended from h1 element

h1 em {color: gray;}
td.sidebar {background: blue;}
td.main {background: white;}
td.sidebar a:link {color: white;}
td.main a:link {color: blue;}
blockquote b, p b {color: gray;}

The child combinator (>):
h1 > strong {color: red;}

Note the difference between descendant and child.

Adjacent-sibling combinator (+) – selects an element that immediately follows another element with the same parent.
To remove the top margin from a paragraph immediately following an H1 element, write:
h1 + p {margin-top: 0;}
In addition, text content between two elements does not prevent the adjacent-sibling combinator from working.
Example: html > body table + ul{margin-top: 1.5em;}
The selector translates as “selects any ul element that immediately follows a sibling table element that is descended from a body element that is itself a child of an html element.”

===============================================================================================

7. Pseudo-Class Selectors

a:visited {color: red;}

:link
Refers to any anchor that is a hyperlink (i.e., has an href attribute) and points to an address that has not been visited.

:visited
Refers to any anchor that is a hyperlink to an already visited address.

The :link and :visited pseudo-class selectors are functionally equivalent to the body attributes link and vlink.
<body link=”purple” vlink=”silver”>

a#footer-copyright:link{font-weight: bold;}
a#footer-copyright:visited {font-weight: normal;}

Dynamic pseudo-classes
:focus

Refers to any element that currently has the input focus i.e., can accept keyboard input or be activated in some way.

:hover
Refers to any element over which the mouse pointer is placede.g., a hyperlink over which the mouse pointer is hovering.

:active
Refers to any element that has been activated by user inpute.g., a hyperlink on which a user clicks during the time the mouse button is held down.

a:link {color: navy;}
a:visited {color: gray;}
a:hover {color: red;}
a:active {color: yellow;}

Note that the dynamic pseudo-classes can be applied to any element, which is good since it’s often useful to apply dynamic styles to elements that aren’t links.

The order of the pseudo-classes is more important than it might seem at first. Recommendation is “link-visited-focus-hover-active.”

:first-child – used to select elements that are the first children of other elements.
Consider the following markup:

<div>
<p>These are the necessary steps:</p>
<ul>
<li>Insert key</li>
<li>Turn key <strong>clockwise</strong></li>
<li>Push accelerator</li>
</ul>
<p>
Do <em>not</em> push the brake at the same time as the accelerator.
</p>
</div>

In this example, the elements that are first children are the first p, the first li, and the strong and em elements. Given the following two rules:
p:first-child {font-weight: bold;} - bolds the p that is a first-child; so “These are the necessary steps” will be bolded.
li:first-child {text-transform: uppercase;} – Set the <li> that is a first-child to upper case; so “Insert key” becomes “INSERT KEY”

For situations where you want to select an element based on its language, you can use the :lang( ) pseudo-class. In terms of its matching patterns, the :lang( ) pseudo-class is exactly like the |= attribute selector. For example, to italicize any element in French, you would write:
*:lang(fr) {font-style: italic;}
The primary difference between the pseudo-selector and the attribute selector is that the language information can be derived from a number of sources, some of which are outside the element itself.

Combine Pseudo-classes
a:link:hover {color: red;}
a:visited:hover {color: maroon;}

8. Pseudo-Element Selectors:

p:first-line {color: purple;}
p:first-letter {color: red;}

In addition, all pseudo-elements must be placed at the very end of the selector in which they appear. Therefore, it would not be legal to write p:first-line em since the pseudo-element comes before the subject of the selector (the subject is the last element listed).

h2:before {content: “]]”; color: silver;} - preface every <h2> with “]]”
body:after {content: ” The End.”;}
- end your document with “The End”

CSS comments

CSS comments:

  • /*   */
  • cannot be nested

Enclose CSS in HTML comment tag

it is recommended that you enclose your CSS declarations in a HTML comment tag because with browsers that don’t recognize <style></style>, the tags within them might not get ignored completely and could cause potential problems for the HTML file.

<style type="text/css">
<!--
@import url(sheet2.css);
h1 {color: maroon;}
body {background: yellow;}
-->
</style>
Posted in CSS. 1 Comment »

@import directive

@import url(sheet2.css);

  • Just like link, @import can be used to direct the web browser to load an external style sheet and use its styles in the rendering of the HTML document. The only major difference is in the actual syntax and placement of the command. @import is found inside the style container. It must be placed there, before the other CSS rules, otherwise it won’t work at all.
  • Like link, there can be more than one @import statement in a document
  • You can’t put an @import into a style attribute, nor can you include any complete rules.

“link” tag

<link rel=”stylesheet” type=”text/css” href=”sheet1.css” media=”all” /> – allows HTML authors to associate other documents with the document containing the link tag.

Alternate style sheets:
<link rel=”stylesheet” type=”text/css” href=”sheet1.css” title=”Default” />
<link rel=”alternate stylesheet” type=”text/css” href=”bigtext.css” title=”Big Text” />
<link rel=”alternate stylesheet” type=”text/css” href=”zany.css” title=”Crazy colors!” />

It is also possible to group alternate style sheets together by giving them the same title value. Thus, you make it possible for the user to pick a different presentation for your site in both screen and print media. For example:
<link rel=”stylesheet” type=”text/css” href=”sheet1.css” title=”Default” media=”screen” />
<link rel=”stylesheet” type=”text/css” href=”print-sheet1.css” title=”Default” media=”print” />
<link rel=”alternate stylesheet” type=”text/css” href=”bigtext.css” title=”Big Text” media=”screen” />
<link rel=”alternate stylesheet” type=”text/css” href=”print-bigtext.css” title=”Big Text” media=”print” />

Reason is because if you give a link with a rel of stylesheet a title, then you are designating that style sheet as a preferred style sheet. This means that its use is preferred to alternate style sheets, and it will be used when the document is first displayed. Once you select an alternate style sheet, however, the preferred style sheet will not be used.

Furthermore, if you designate a number of style sheets as preferred, then all but one of them will be ignored. Consider: (3 different titles)

<link rel=”stylesheet” type=”text/css” href=”sheet1.css” title=”Default layout” />
<link rel=”stylesheet” type=”text/css” href=”sheet2.css” title=”Default text sizes” />
<link rel=”stylesheet” type=”text/css” href=”sheet2.css” title=”Default text sizes and layouts” />

Element definitions

  • Replaced elements – the element’s content is replaced by something that is not directly represented by document content. For example, <img>
  • Nonreplaced elements – their content is presented by the user agent (generally a browser) inside a box generated by the element itself. For example, <span>hi there</span> is a nonreplaced element, and the text “hi there” will be displayed by the user agent.

  • Block-level elements generate an element box that (by default) fills its parent element’s content area and cannot have other elements at its sides. In other words, it generates “breaks” before and after the element box. The most familiar block elements from HTML are <p> and <div>.
  • Inline-level elements generate an element box within a line of text and do not break up the flow of that line. The best inline element example is the <a> element in XHTML. Other candidates are <strong> and <em>.

ASP.NET Page Info

runat=”server”

The only way for an ASP.NET page to realize that you are using a server control (like asp:Textbox or input type=”text”) is to have runat=”server” in the control tag. This is very important; forgetting it will cause the ASP.NET engine to pass over the control as HTML.

Validation Controls

ASP.NET supplies 6 different validation controls, each with some distinct properties besides the few common ones:

  • RequiredFieldValidator
  • RangeValidator
    • MaximumValue (In code behind, MaximumValue=DateTime.Today.ToString(“yyyy/MM/dd”))
    • MinimumValue (1850/1/1)
    • Type (String or Date)
  • RegularExpressionValidator
    • ValidationExpression – put in regular expression here. There are a few of pre-defined ones.
  • CompareValidator
    • ControlToValidate & ControlToCompare
  • CustomValidator
    • Double-click on design mode to get the event handler on server-side
      e.g. args.IsValid == (args.Value.Length >= 8 )
    • clientValidationFunction (JavaScript)
      e.g.
      function isLengthValid (source, args)
      {
      args.IsValid = (args.Value.Length >= 8 )
      }
    • Both client- and server-side validation function should be included
  • ValidationSummary
    • HeaderText
    • CssClass
    • DisplayMode
  • Common properties:
    • ControlToValidate – this is the most essential obvisouly, a must
    • ErrorMessage – Text in here will be displayed in the ValidationSummary
    • Text – This will be displayed right at where the validation control lies
    • Display (Static/Dynamic/None) – pretty intuitive. I see “dynamic” being the default, because it doesn’t take up space when it’s not being validated. There is no reason for some empty place holder.
    • EnableClientScript – default is true; if browser supports JavaScript, then validation is done on client first. If the validation fails, then postback is cancelled.
    • ValidationGroup – Just give it a name, and give the same name to the button or whatever control that is to trigger the validation, then only the fields with the same group name will be validated.
      Uses:
      Page.Validate(ValidationGroupPropertyValue) – tells the page to perform validation on fields with that specified validation group
      GetValidators(ValidationGroup) – returns a collection of validation controls that belong to the specified validation group
    • SetFocusOnError – same as the Focus() method; if set to True, causes the Web control the validation control is operating on to receive focus if the validation control is invalid

Example: To validate a password, should use the following validation

  • RequiredFieldValidator
  • RegularExpressionValidator
  • CompareValidator (for the re-type password field)
  • CustomValidator (To check length of password)

More references: