Display & Position

Introduction to Cascading Style Sheets

What is CSS?

CSS is a style sheet language used for describing the presentation semantics (the look and formatting) of a document written in markup language. It's most common application is to style web pages written in HTML and XHTML, but the language can also be applied to any kind of XML document, including plain XML, SVG, and XUL.


Why use CSS?

CSS was developed back in 1996 to provide a separation of concerns from information content & details of how to display it.

There are no real alternatives to CSS, but there are many tools which have found ways to improve on certain aspects of the CSS coding practices. The end result will always be produced as plain old CSS, but alternatives like LESS CSS can let you be more productive when writing your code.


How to use CSS

There are three specific ways to add CSS to the elements of your document.


Method 1: Use an External Stylesheet

This method involves adding a reference to an external document with the .css extension in the <head> of your document using the <link> tag.

Example:
 1 <!DOCTYPE html>
 2         <html>
 3         <head>
 4             <title>CSS Lunch and Learn</title>
 5             <link rel="stylesheet" type="text/css" href="css/style.css">
 6         </head>
 7         <body>
 8             <p>Hello World!</p>
 9         </body>
10         </html>

Method 2: Internal Style Sheet

An internal stylesheet, is when you wrap a block of CSS declarations in a <style> tag inside the <head> of a document.

Example:
 1 <!DOCTYPE html>
 2         <html>
 3         <head>
 4             <title>CSS Lunch and Learn</title>
 5             <style type="text/css">
 6             body {
 7                 background:#39F;
 8                 font-family:Arial;
 9             }
10             p {
11                 font-size:14px;
12             }
13             </style>
14         </head>
15         <body>
16             <p>Hello World!</p>
17         </body>
18         </html>

Method 3: Inline Styles

Inline styles are styles added directly to the element that you are trying to style, in the HTML document itself. The styles are collected into a style attribute

Example:
1 <!DOCTYPE html>
2         <html>
3         <head>
4             <title>CSS Lunch and Learn</title>
5         </head>
6         <body style="background-color:#39F; font-family:Arial;">
7             <p style="font-size:14px">Hello World!</p>
8         </body>
9         </html>
 For a more detailed introduction to to including styles in your HTML documents, read the W3Schools article

Working with CSS can be a real joy, and offers you a whole world of possibilities when it comes to formatting information in a creative fashion. Being smart with how you write your CSS enables you to be more productive, with a lighter footprint in your code.

Box Model

Everything on a web page is a box. Whether square or rectangular, every element you see on a web page has an aspect we refer to as the box-model. I tend to think of the elements similar to a set of infinitely customizable leggos, where you define their color, length, width, and position.

Resources:

Element Selectors

CSS Element Selectors do exactly as the name describes. They select an element from a web page and manipulate it's presentation by adding properties to that selection.

We will start with some plain basic HTML, with six selectable elements - html | body | div | h1 | p | a

 1 <!DOCTYPE html>
 2         <html>
 3             <head>
 4                 <title>CSS Lunch and Learn</title>
 5             </head>
 6             <body>
 7                 <div>
 8                     <h1>Heading</h1>
 9                     <p>Paragraph</p>
10                     <a href="#">Link</a>
11                 </div>
12             </body>
13         </html>
The Result:

View the result 


Now lets style our example HTML with some basic CSS selectors:
 1 body {
 2             font-family:Arial;
 3         }
 4         div {
 5         	padding:5px;
 6         	box-shadow:0px 0px 5px 0px #000;
 7         	background-color:#eee;
 8         }
 9         h1, p, a {
10             line-height:1.2;
11         }
12         h1 {
13         	margin-bottom:15px;
14         	font-size:24px;
15         	text-decoration:underline;
16         	font-variant:small-caps;
17         }
18         p {
19         	font-size:14px;
20         	margin-bottom:10px;
21         }
22         a {
23         	color:#09f;
24         	text-decoration: none;
25         }

View the result 


We used the most basic of selectors, the element selector, to select the parts of the page we wanted to style, and then applied some styling declarations to those selectors to create a desired result. Although this works well for styling elements, we would quickly run out of presentation options, and our designs would be pretty plain.

Unless you are building a very simple web page, you generally want to avoid targeting elements, and instead target a wrapping class or ID, and then drill down to the element you are wanting to manipulate.

Class & ID Selectors

CSS allows you to specify your own semantic selectors with the Class & ID system.

HTML with Classes & IDs added:
 1 <!DOCTYPE html>
 2       <html>
 3         <body>
 4           <div id="mainContent" class="wrapper">
 5             <h1 class="title">My First Heading</h1>
 6             <p class="headline">My first paragraph.</p>
 7             <a class="affiliate" href="#">My first Link</a>
 8           </div>
 9         </body>
10       </html>

Here is a brief example of how to target those classes and IDs.

 1 body {
 2             font-family:Arial;
 3         }
 4         h1, p, a {
 5             line-height:1.2;
 6         }
 7         .wrapper {
 8             padding:5px;
 9             box-shadow:0px 0px 5px 0px #000;
10             background-color:#eee;
11         }
12         .wrapper .title {
13             margin-bottom:15px;
14             font-size:24px;
15             text-decoration:underline;
16             font-variant:small-caps;
17         }
18         .wrapper .headline {
19             font-size:14px;
20             margin-bottom:10px;
21         }
22         .wrapper .affiliate {
23             color:#09f;
24             text-decoration: none;
25         }

With the previous example you can see that we made our broad declarations at the top of the stylesheet, and got more specific as we went down.

On line #4 we used the multi-selection syntax to select all of the text nodes we know we want to have a certain line-height. To select multiple elements with the same declaration, you only need to separate those selectors with a comma, and each one will collect the declared styles

On line #12 we see our first specific element selector. We could have very easily also done:

1 .wrapper h1 {
2             margin-bottom:15px;
3             font-size:24px;
4             text-decoration:underline;
5             font-variant:small-caps;
6         }

The potential problem with that solution is now we have isolated all <h1> tags that may appear under the .wrapper div and atrgeted for that style. Aside from the SEO issues from using multiple <h1> tags on a page, you never want to target an element by it's tag name unless you are absolutely positive that the design calls for that behavior, and no other elements will be effected further down the line.

Using two class names has a higher specificity than a class selector and an element selector, a topic we will cover further down the page.

Pseudo Class Selectors

A pseudo class is a keyword added to selectors that specifies a special state of the element to be selected.

Common Pseudo Selectors:
  1. :hover
  2. :visited
  3. :before
  4. :after

All pseudo selectors will be preceded by a colon, and the selector they are targeting.

1 a:hover {
2             text-decoration:underline;
3         }
4         .nav-item:visted {
5             color:#37f;
6         }

Resources:

Specificity

Specificity is the means by which a browser decides which property values are the most relevant to an element and gets to be applied. Specificity is only based on the matching rules which are composed of selectors of different sorts.

In case of specificity equality, the latest declaration found in the CSS is applied to the element.


One way to visualize specificity is with three comma separated numbers:

0, 0, 0

Each number correlates to a type of selector, and the specificity that comes along with it. Specificity also moves from left to right. The left most number is the most specific, while the right sided number is the least specific.

The furthest left number is the most specific, and correlates to ID's. ID's have the highest specificity for a selector used in external CSS, and should be used with caution when targeting elements.

The middle number correlates to classes. Any time you target an element only by it's class name, you are using medium specificity to target it.

The furthest right number is the lowest specificity, and correlates to selecting elements by their HTML tag name. The lowest specific way to target anything on a web page.


For example, lets start with a little bit of HTML and step through all of the levels of specificity.

 1 <!DOCTYPE html>
 2       <html>
 3         <body>
 4           <section id="content">
 5             <article class="post">
 6                 <h2 class="headline">Some BLog Post Title</h2>
 7                 <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, 
 8                 feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi 
 9                 vitae est. Mauris placerat eleifend leo. <a class="read-more" href="#">Read More</a></p>
10             </article>
11           </section>
12         </body>
13       </html>

Our goal is to target the <a> tag wrapped in the <p> tag, the deepest nested element in our example.

The simplest, and least specific way to select the element is by calling it simply by the element outright in the CSS:

1 a {
2             color:#333;
3         }

This selector will produce the lowest specificity possible:

0, 0, 1

This is poor specificity because now we are coloring every link on pages where this snippet of CSS is included grey, which probably is not be ideal. Let's look at the specificity of targeting the <p> tag and the link.

1 p a {
2             color:#333;
3         }
0, 0, 2

We are a little more specific, but still not really encapsulating our selector enough to ensure that we are targeting the proper element at all times. Let's start using the class name of the wrapping element to be more specific.

1 .post p a {
2             color:#333;
3         }
0, 1, 2

It looks like we have a class name tied to the anchor link we are trying to target, so we can also go ahead and use that class name instad of just targeting the <a> tag.

1 .post p .read-more {
2             color:#333;
3         }
0, 2, 1

This is usually as specific as someone needs to get to ensure that you are both targeting the element you want to target, and excluding all of the elements you don't want collecting unwanted styles. Of course, it will always depend on the problem at hand, and the type of website or application you are working on. It is always a bit safer to go more specific than less, but you want to be careful and not have your selectors become too specific, forcing you to create many selectors in your CSS that do a lot of the same things.

Using the same HTML example above, the most specific selector we can come up with from that HTML would be as follows (excluding the <html> & <body> tags).

1 #content article.post p a.read-more {
2             color:#333;
3         }
1, 2, 3

Resources:


Visual Studio's Web Essentials plug-in comes with a handy specificity feature, which will visualize your selectors specificity when you hover over it.

!important

Related to specificity is the !important declaration. !important is used after you make a CSS declaration, before the line ending semi-colon.

1 p {
2             color: #000 !important;
3         }

The only way to override an !important declaration, is to declare another !important specification later in the CSS, or to add an inline style. As CSS cascades, the last declaration with matching specificity will be applied.

1 p {
2             color: #000 !important;
3         }
4         a:hover {
5             text-decoration:underline;
6         }
7         p {
8             color:#06f !important;
9         }

In the previous example, the last p selector will be applied, because it is the last selector to target that element with !important declared.

 !important is your best friend and worst enemy! Chances are that if you are using it, you are doing something wrong. It is an edge-case property that should be saved for times when there is literally no other options available.

Overriding inline styles

One of the few times !important is used well, is when you need to override an inline style applied to an element dynamically, and you do not have access to the source code, or cannot change the source-code for a certain display option.

1 <div id="newsletterSignup" style="display:block; position:absolute; top:20px; left:200px;">
2             <input type="text" name="email">
3             <a href="somepage.html" title="Sign up now!">Sign up now!</a>
4         </div>

Assume that the above div is coming in from a third-party plug-in, and is getting some inline styles added to it that are throwing it out aof alignment, and cutting off the content. Just targeting the CSS ID #newsletterSignup would not work, even though an ID has the highest specificity, and it is the correlating name of the element.

1 #newsletterSignup {
2             left:100px !important;
3         }

This would not work to override an inline style. To be clear, you would be seeing your desired result, but you would be targeting the element as a whole, and applying that positioning to that element, rather than simply overriding inline styles, and preventing further conflicts.

1 #newsletterSignup[style] {
2             left:100px !important;
3         }

Now you are targeting the inline styles attached to that ID. However, you still need to use !important to effectively override the applied inline CSS styles, and get the div to render as desired. Because inline styles have the highest possible specificity, !important is your only saving grace in these matters.

 The [style] selector is a great tool to have in any designers belt. However, as you would suspect, IE7 does not support it. In these cases, one best practice would be to use a Conditional Comment and target the fix per browser.