Friday 2 November 2012

Introduction To CSS Concepts

This note is a reminder about CSS concepts, together with links and other useful pages or summaries. CSS stand for Cascading Style Sheets. These sheets are used at the presentation layer to apply styling (fonts, colors, layout...) to HTML documents.

HTML Concepts Reminder

HTML documents contain text and tags (also called markup). The following body of a HTML document contains a paragraph <p> tag:
...
<body>
  <h3>Some header</h3>
  <p class="myClass" >This is a paragraph!</p>
</body>
...
This tag has an attribute called class. Since HTML5, documents are represented as a tree structure (DOM) in browsers, where each tag is a node.

CSS Rule

CSS sheets are electronic documents containing rules. For example:
h3 { color: green; }
A rule contains one or more selector (h3), with a declaration block ({ color: green; }). Declarations are made of pairs of properties (color) and values (green). They are separated by semicolons. The above rule tells the browser displaying the HTML document to find all <h3> tags, and apply the green color to the corresponding content.

Style Types & CSS Reset

By default, each browser has its own style which it automatically applies on HTML documents, unless specific CSS style is declared in the HTML document. There are differences between browsers' default styles. Therefore, identical documents will be displayed differently on different browsers.

The solution is to use a CSS reset style sheet, which eliminates those differences.

There are different types of CSS styles:
  • Inline Style - Styling can be applied directly on HTML markup with the help of the style attribute. It prevails on all other styles in case of conflict, since it is considered the most specific. In the following example, no matter what, the green color will be applied on this paragraph:
<p style=”color: green;”>This is a paragraph!</p>
  • Embedded Style - If you want to apply a style to a whole document, for example, make all paragraphs green, you can used embedded styling with the <style> tag as following:
<!doctype html>
<html>
  <head>
    <meta http-equiv="Content-Type"
      content="text/html; charset=UTF-8">
    <title>My HTML Document!</title>
    <style type="text/css">
      p { color: green; }
    </style>
  </head>
  <body>
    <p>This is a paragraph!<p>
    <p>This is another paragraph!<p>
  </body>
</html>
  • External Style (linked) - This is the most common type of CSS styling. Every CSS rules are stored in separate files and a links to those files are included in HTML document headers:
...
<head>
  <link rel=”stylesheet”
    type=”text/css” src=”style/global.css”>
  ...
</head>
...
It is considered a good practice to separate HTML markup from styling. Hence, using external style sheets is the way to go. However, it creates an issue, how to apply styling to a unique HTML element? The solution is to use id selectors, or class selectors for groups of HTML elements. We will cover this later.

Using @import

@import is CSS command used to import external CSS stylesheet. For example, large CSS files can be split in several sub-files. The main file can use @import to import them. The HTML document only needs to link to the main CSS document:
@import url('/mycss/part1.css');
@import url('/mycss/part2.css');
@import url('/mycss/part3.css');
...
With @import, there is an extra way to import CSS stylesheets in HTML documents:
  
...
<head>
  <meta http-equiv="Content-Type"
    content="text/html; charset=UTF-8">
  <title>My HTML Document!</title>
  <style type="text/css">
    @import url('/mycss/part1.css');
    @import url('/mycss/part2.css');
    @import url('/mycss/part3.css');
    ...
  </style>
</head>
...

Inheritance

By default, when a, inheritable property is applied to a HTML tag, it is applied to all the children elements too. If the following rule is applied:
p { color: green; }
on the following document:
...
<body>
  <p>This is some code: <code>var a = 2;</code></p>
</body>
...
The green color property is applied not only on <p>, but also on <code>. Otherwise, we would have to define a rule for <code> too, which can be tedious if a document has many parent-child relationships.

On the other side, if we want to make sure a child element has the same property value as its parent, we can use the inherit CSS keyword:
code { color: inherit; }
In this case, no matter where <code> is used, the color of the corresponding content will match that of the parent. Not all properties are inherited (border for example).

Selectors

There are several types of selectors in CSS:
  • Universal Selector - Selects all elements in the HTML document:
* { color: green; }
  • Element Selectors - Selects specific elements in the HTML document from there tag types (for example p for all paragraphs <p>):
p { color: green; }
  • Class Selectors - Selects all elements having a class attribute with the corresponding value. Here, "Some text" will be displayed in green:
<p class=”myClass”>Some Text</p>  // HTML

.myClass { color: green; }        // CSS
  • ID Selectors - Selects the element having an id attribute with the corresponding value. Here, the div element will have a width of 500 px:
<div id=”section1”> . . . </div>  // HTML<

#section1 { width: 500px; }        // CSS
  • Pseudo Class Selectors - Pseudo class are, for example, used change the color of links:
a:link { color: green }
  • Child Selectors - For a given element, this selector allows the selection of the children in the DOM hierarchy. The following will select all paragraphs within div sections:
div > p { color: green;}
  • Attribute Selectors - Selects HTML tags having a specific attribute. Here the attribute is title:
[title] { color: green; }
It is possible to apply many classes to an HTML tag (Multi-Classing):
<div class=”class1 cooking”> . . . </div>
One can group selectors to apply common properties, by separating them with commas:
p, h1, #myid, .myclass { color: green; }

Cascading

CSS stands for Cascading Style Sheets. Why cascading? Because multiple style sheets can be applied to the same HTML document before displaying (from highest to lowest priority):
  1. Author Styles - Any inline and embedded styles, together with external style sheets defined in the HTML document by its author.
  2. User Style - Although this is rarely the case, end users can configure a style sheet in their browser.
  3. Browser Style - By default, every browser has its own style sheet to applies if not author or user style is available.
The highest available style is applied.

Specificity

In case of conflicting CSS rules when applying styling, the prevailing rule will be the one having the higher selector specificity, for a given HTML tag.

A CSS rule's specificity is computed using a hierarchy of selector categories:
  1. Inline styling (<p style=”color: green;”>...</p>)
  2. Ids (#myid1, #myid2,...)
  3. Classes, attributes and pseudo-classes (.myClass1, .myClass2...)
  4. Elements and pseudo elements (h1, p, li, ul...)
The rule's selectors must be counted in each category. For example:
h1 em#myid { color: green }
has a specificity of 0-1-0-2 (one id, two elements). 

Inline styling beats all CSS rules. If rule1 has more ids in its selector than rule2, then rule1 prevails on rule2. If they have the same number of ids, then one should repeat the comparison by counting classes, attributes and pseudo-classes, etc...

If two rules have exactly the same specificity, the last one declared prevails. The universal selector * and inherited selectors have a specificity of 0, 0, 0, 0.

The important! Keyword


This is a CSS feature you should probably avoid in most circumstances. Basically, it overrides the specificity process. For example, the following CSS:
h1 { color: yellow !important; }
#myid { color: green; }
applied on the following HTML:
 <p id="myid">Some text!</p>
will display a yellow text, rather than a green text.

The Box Model

It is possible to define boxes for content in CSS. The content has height and width. The padding is the space between this content and its border. The border has a thickness. The margin is the additional space around the border.


The above box model can be declared as following:
.myid {
   width: 200px;
   height: 50px;
   padding: 8px 11px 4px 7px;
   border-style: solid;
   border-width: 9px 1px 3px 6px;
   margin:10px 12px 2px 5px;
}

Float Behavior

The float property allows one to push elements (such as images for example) to the left or to the right. The other elements or text will wrap around. Yet, if you push too many elements to the left, there may not be enough width space on the screen to display them all. The browser will display them on the next line.

Hence, the position of such elements is not fixed. It depends on the size of the browser screen.

Positions

Each element in a HTML document has a position property value:
  • static - This is the default position of all elements. It means the element should be displayed where it should be displayed naturally in the document.
  • relative - This is mean the element should be positioned relatively to its naturally position. One can add 10 pixels to the left, for example. The final position can be impacted by any float behavior.
  • absolute - This allows to position an element at a precise position. This will be relative to the first parent having an absolute or relative position. If none is available, it will be positioned relative to the page itself.
  • fixed - This allows the positioning of an element relative to the display window. It will not move when the page is scrolled up or down, and remain visible.

z-index

If you have several images (or other items) overlapping each other in a HTML document, the z-index will help define which one should be on top and which one should be on the bottom. The higher the value, the closer to the top:
img {
 position:absolute;
 left: 100px;
 top: 100px;
 z-index: 30;
}

Media Queries

Media queries are a means to apply CSS rules conditionally. For example, one can check the available width of the screen and decide to display more or less information. This avoids having to develop separate HTML pages with separate CSS for different devices.

1 comment:

  1. Great article Jerome and a precise explanation of padding and margin.

    ReplyDelete