CSS

Much ado about CSS Selectors

0

CSS can be daunting to the newbie or even to the expert. This tutorial is a guide to selectors that you may (or may not) already know about. This tutorial assumes you already have a foundation of CSS (or at least understand the basic syntax).

To avoid any potential confusion here is a basic example of what selectors look like...

selector { property: value; } /* single line statements */
selector { /* multi-line statements */
    property: value;
    property: value;
}

Below are the most common selectors we all encounter in a daily basis. We'll go over the basics of these selectors. Feel free to skip this section if you believe you have a firm understanding.

The Players

Entity Selectors

Perhaps the best way to actually begin learning CSS is to start with the existing HTML elements before incorporating created ones.

Entity selectors, as we like to call them, are selectors that style HTML elements. For consider:

body { width: 960px; }

The above code sets the width of the body element to 960px. Pretty straight forward right? Let's see more examples.

body {
        margin: 0 auto;
        width: 960px;
        font: normal 12px verdana, sans-serif;
        color: #888;
}
p { line-height: 1.2em; }
a {
        color: blue;
        text-decoration: underline;
}

The above code styles the body element, the p element, and the a element. This ends our venture into the HTML entity selectors.

ID Selectors

ID selectors are our first venture into artificial elements we can style. Let's view an example off the bat:

<style type="text/css">
#nav {
        clear: both;
        background: blue;
        padding: 3px 0;
}
</style>
<div id="nav">
  <ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">Services</a></li>
    <li><a href="#">Support</a></li>
  </ul>
</div>

We can create phony elements that we can style via HTML/CSS. We indicate any ID selectors (IDs) via the id attribute in HTML. We denote IDs via the use of a "hash" tag/pound sign (#) before the name of the selector.


Note: we must cover something very very important. Both ID and CLASS selectors cannot begin with a number or special character. In fact, use nothing other than capital/lowercase letters, numbers, hyphens (-), and underscores (_) in your selectors. Let's see some examples...

#1blah { clear: both; } /* BAD */
#blah1 { display: block; } /* GOOD */
#blah_1 { top: 13px; } /* GOOD */
#blah+1 { float: left; } /* THIS DOES NOT EQUAL</pre>
<div id="blah+1">*/
#blah-1 { font-weight: 700; } /* GOOD */

Now that we have go over selector naming conventions... Let us continue:

ID selectors have a very important feature that we must be conscious of in order for our code to validate. We can only use an ID in HTML once per HTML page. IDs can be thought of as identification so it has to be unique and there is only one of them per page.

<!-- this is bad -->
<div id="item"></div>
<div id="item"></div>

Class Selectors

Class selectors are, perhaps, the most commonly used selectors. Unlike IDs, class selectors (classes) can be used multiple times within the same document. Let's see an example:

p.big { font-size: 16px; }
.underline { text-decoration: underline; }

 

<p>This is some text</p>
<p class="big">This is some <span class="underline">BIG</span> text</p>
<p class="big">Big text</p>

The output from the above would be:

This is some text This is some BIG text Big text

Class selectors are denoted by the use of a "." before the name of the selector.

Pseudo-Class Selectors

Despite the daunting name, these guys are very easy to understand and to use. We encounter these selectors on a regular basis and are often implemented globally. Let's look at an example first and foremost. This is a linkThere you are, you have now seen a pseudo-class selector (pcs) in action! What exactly did you see/do you might ask? The simple act of rolling over the link, causing an action to happen, is a pcs. Here are the most common selectors we encounter on a day-to-day basis. There are more but these will be covered later on.

/* NOTE: The ordering of these selectors must be as follows */
a, a:link { /* unvisited link */
        color: #ccc;
        text-decoration: underline;
}
a:visited { color: #666; } /* a previous visited link */
a:hover { /* what happens when you roll over the link */
        text-decoration: none;
        background: #ccc;
        color: white;
}
a:active { color: green; } /* what happens when you click on the link */

Why are these called pseudo-classes you might be wondering? Let's look at some code!

a { text-decoration: underline; }
a.hover { text-decoration: none; }
a.active { color: green; }
<!-- no roll over styled by a {} -->
<a href="#"></a>
<!-- upon roll over styled by a.hover {} -->
<a href="#" class="hover"></a>
<!-- upon click styled by a.active {} -->
<a href="#" class="hover active"></a>

Imagine when we mouse over an anchor tag our browser automatically appends the class "hover" to our anchor tags. When we click on a link, our browser automatically appends the "active" class. When we move our mouse away the "hover" class is removed. This is basically what happens with pseudo-classes. We can think of these as classes that are inherently understood by the browser and the browser checks to see if various elements are hovered over, visited already, active, etc. As much simpler way of accomplishing styling of links is via:

/* style main links */
a, a:link, a:focus { }
/* styles to show when the link has been visited already */
a:visited {}
/* styles to show when mouse is over link */
a:hover {}
/* styles to show when the link is clicked */
a:active {}

Typically, general practice (at least for us) is as follows:

a, a:link, a:focus, a:visited {}
a:hover, a:active {}

Grouping Selectors

a, a:link, a:focus, a:visited { color: green; }
a:hover, a:active { color: blue; }

What is significant about this code other than the use of Pseudo Classes one might inquire? You'll come to notice that these selectors are all separate and share the same styles. CSS is very friendly and enables us to group selectors together in order for them to share styles. Let's dissect the code above: a, a:link, a:focus, a:visited all share the same styles. This means that all basic links (when focused upon of visited) will have the color of green. a:hover, a:active will share the same styles (when hovered over or clicked on) and the color of the text will be blue. Pretty easy right? Let's take a look at inheritance.

blockquote, div.indent {
    color: #666;
    padding-left: 15px;
    font-weight: normal;
}
div.indent { font-style italic; }

We can see that we have blockquote, div.indent grouped together and are sharing the same styles. What if we want to allow div.indent to have most of the same styles as blockquote? This is an inheritance issue. We give the two elements the same styles but we want div.indent to have italic font. We can accomplish this by writing a new styling definition for this selector. Seems simple enough, right? What if we want a style for div.indent to override something in a grouping?

blockquote, div.indent {
    color: #666;
    padding-left: 15px;
    font-weight: normal;
}
div.indent { color: #ccc; }
Remember: CSS stands for Cascading Style Sheets. Cascade means to go in a sequence. CSS will only override preexisting styles if the definition comes after any previous style definitions.
div.indent { color: #ccc; }
blockquote, div.indent {
    color: #666; /* this overrides the color in div.indent */
    padding-left: 15px;
    font-weight: normal;
}
blockquote, div.indent {
    color: #666;
    padding-left: 15px;
    font-weight: normal;
}
div.indent { color: #ccc; } /* this overrides the color defined in blockquote, div.indent */

The styles are the same but the position of the styles within a style sheet make a BIG difference how they are rendered.

Nesting

To continue a lesson inheritance, we will now discuss nesting selectors in CSS. Let's look at an example:

blockquote {
    margin: 0;
    padding: 0;
    -moz-box-shadow: 0 0 5px 2px #ababab;
    -webkit-box-shadow: 0 0 5px 2px #ababab;
    box-shadow: 0 0 5px 2px #ababab;
    border: 1px solid #ababab;
}
blockquote .inner {
    -moz-box-shadow: inset 0 0 5px 2px #ababab;
    -webkit-box-shadow: inset 0 0 5px 2px #ababab;
    box-shadow: inset 0 0 5px 2px #ababab;
    border: 1px solid #ababab;
    padding: 15px 5px;
    margin: 0 5px;
}

And the HTML:

<blockquote>
     <div class="inner">Lorem ipsum...</div>
</blockquote>

In the terms of inheritance we have a parent blockquote and a child .inner. Nesting selectors implies a parent > child > grandchild > great-grandchild > and so on relationship. The simplest of these relationships is a parent-child relationship. The number of nesting you can do in CSS is only limited to how much your server can handle. The important concept to grasp with nesting elements in CSS is that your browser will assume that:

parent child { }

Means:

<parent>
     <child></child>
</parent>

And all styling done with the parent child {} will apply ONLY to the <child>element. Let's see another example!

#nav {
    width: 100%;
    border: 1px solid white;
}
#nav li { background: #ccc; }
#nav li a { color: black; }
#nav li.current { background: #222; }
#nav li.current a { color: white; }

 

<ul id="nav">
	<li><a href="#">Item</a></li>
	<li><a href="#">Item</a></li>
	<li><a href="#">Item</a></li>
	<li><a href="#">Item</a></li>
</ul>

So what's going on here anyway? We're creating a simple navigation menu so let's dissect some code:

#nav {
    width: 100%;
    border: 1px solid white;
}

This is our ID element (we only will have one of these per page). With the code above we're setting the width of the #nav element and wrapping it in a white border. Next:

#nav li { background: #ccc; }

We are nesting the #nav and li element (#nav being the parent and li being the child. We are styling:

<ul id="nav">
     <li></li>
</ul>

We can think of this as the following: where the li element is a child of the element that has the id of #nav, put a gray background on the lielement where these conditions are true. Here is a pseudo code version of what we described above:

if "li" is a child of an element that has an id of "nav"
    then, add a background of "#ccc"

Sibling Selectors

Siblings are defined as two or more objects that come from the same parent. For example:

.parent1 .sibling1.sibling2 { }

ID attributes DO NOT allow for multiple values within the ID field!

<div id="item1 item2"></div>

Will not validate!

The benefit of class attribute values is that we can use multiple class values within this attribute field. For instance:

.parent .child_1 { color: blue; }
.parent .child_1.child_2 { color: red; }
.parent .child_2 { color: green; }
.parent .child_3 { color: lightblue; }
.parent .child_4 { color: gray; }
<div class="parent">
    <p class="child_1">Text</p>
    <p class="child_1 child_2">Text</p>
    <p class="child_2">Text</p>
</div>
<div class="parent">
    <p class="child_3">This is lightblue</p>
    <p class="child_4">This is gray</p>
    <p class="child_3 child_4">This is gray</p>
</div>

Let's take a look at this code, shall we? We have a parent selector .parent and we have two children elements .child_1 and .child_2.

  1. When child_1 is within the parent element, make the text color blue
  2. When child_1 and child_2 are siblings, make the text red
  3. When child_2 is within the parent element, make the text color green
  4. When child_3 is within the parent element, make the text color lightblue
  5. When child_4 is within the parent element, make the text color gray

Let's actually see the rendered result: http://jsfiddle.net/atomicpages/b7Yuk/

What's exactly happening in our last example:

This is gray

Why would this text be gray? Would it be gray as the text suggests?
Indeed, the text would be gray as the text suggests because we are cascading styles. Because the color value described in child_4 is being called after child_3, we see the styles described in child_4. What if we had the code <p class="child_4 child_3">This text will be gray</p>. Will this text be gray or will it be lightblue?

Pseudo Element Selectors

Pseudo Elements Selectors (PES) behave the same way as normal elements. The only exception being that PES aren't actual elements. Here is a list of PES:

  • :first-line
  • :first-letter
  • :before
  • :after
:first-line

Consider the following code:

p:first-line { font-weight: bold; }

 

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Cras accumsan sapien eu urna adipiscing mattis.</p>

At first glance this may seem strange but we can assume, based on the PES, that we are styling the first line of the <p>element. Let's see a different approach:

<p><span:first-line>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span:first-line>
Cras accumsan sapien eu urna adipiscing mattis.</p>

We are imagining that Lorem ipsum dolor sit amet, consectetur adipiscing elit. is the first line of this element. It's important to know that the first line is always relative to the width of a parent container. For example: I have a width of 100px

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras accumsan sapien eu urna adipiscing mattis.

I have a width of 400px

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras accumsan sapien eu urna adipiscing mattis.
:first-letter

Similar to the :first-line PES, the :frist-letter PES styles the first letter of the matching element.

p:first-letter { font-size: 2em; }
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras accumsan sapien eu urna adipiscing mattis.</p>

Our result would be:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras accumsan sapien eu urna adipiscing mattis.
:before

The :before PES differs from first-letter or first-line greatly. The :before PES actually treats the area before an element as an autonomous entity. Let's observe some code:

<p class="before"></p>
<p>content</p>

We can consider p.before as it's own element because that's essentially what :before does to begin with. Let's see a realistic example:

<p class="upload">This is some text</p>
p.upload { font-size: 16px; }
p.upload:before { background: transparent url('upload.png') 0 0 no-repeat; }
:after

Similar to :before, the :after PES does the exact opposite of what :before does. Instead of treating the area before the element as an element, we're treating after the element as an element. Here is a very common real-life example:

<nav>
     <ul>
          <li><a href="#">Sample</a></li>
          <li><a href="#">Sample</a></li>
          <li><a href="#">Sample</a></li>
     </ul>
</nav>
nav {
     display: block;
     margin: 0;
     padding: 0;
     background: #ccc;
     float: left;
     width: 50%;
}
nav:after {
     display: block;
     clear: both;
     content: '\0020';
}
nav ul {
     margin: 0;
     padding: 0;
}
nav ul li {
     float: left;
     margin-right: 8px;
}
nav ul li a {
     color: white;
     text-decoration: none;
     font-weight: normal;
}
nav ul li a:hover { color: black; }

Since we're setting the width of our nav element to 50%, this means elements that are not floated can actually start wrapping around the nav element where there is whitespace. We have a few options here, we can clear each non-floated element that this may happen to on a dozen or so pages or we can have one CSS rule that says after this nav element we want a display a block, clear left and right floats, and add some weird content thing.

So what exactly is content: '\0020';? The code \0020 is just a space (literally -> ' '). Some people will do content: '.'; or some will use a 1px by 1px transparent gif called blank.gif to help escape floated elements. If we're dealing with responsive designs, Android navtive browser (at the time of this writing) actually showed content: "."; so I like to use \0020 instead.

Here is an exmaple on jsfiddle showing ALL of the PESs that we just covered! http://jsfiddle.net/atomicpages/FumgJ/

Direct Descendant Selectors

Although, the name I use is not the actual name, it helps me think about what these selectors do. First, let's look at the syntax because we use a unique symbol to indicate parent-child relationships using direct descendant (dd) selectors.

div p { color: red; } /* regular */
div > p { color: red; } /* dd */

So what makes these selectors unique anyway? It's all about optimization, baby! Let's look at some more code:

<div class="parent">
     <p>Text</p>
     <div>
          <p>More Text</p>
     </div>
</div>
div p { color: red; }

The above CSS will produce a potentially undesired result here. This will make all of our p elements within div red. No matter how many elements we have below <div class="parent"> they will be red unless otherwise overridden. What if we don't want that? What if we only want children of div.parentto be red?

div.parent p { color: red; }

Will that work? Of course not! I mean... we can make it work if we wanted to with extra code, but why write more code when we don't need to?

div.parent > p { color: red; }

Ahhh yes! This will work! All p children elements of div.parent will now be red and we didn't need to write extra code to override styles. Again, here is another fiddle showing a live example: http://jsfiddle.net/atomicpages/YWuHD/

Adjacent/Sibling Selectors

We touched base on sibling selectors with two class selectors. When we refer to siblinghere we mean two selectors that are adjacent to each other (the W3C doesn't explain this distinction very well). To recap, here is a sibling relationship between class selectors:

.item.one { ... } /* <div class="item one"></div> */

These adjacent/sibling selectors in this case also use a symbol similar to our direct descendant selectors:

div + dl  { padding-left: 25px; }

 

<form>
     <div>This is some text...</div>
     <dl>
          <dt>Term</dt>
          <dd>Definition</dd>
     </dl>
</form>

It is said that div and dl are siblings because they some from the same parent form in our case. Using this selector can be very useful when styling elements that lack any attributes, class values, or ids. I believe with this selector in particular, it's best to see an example. Here is a fiddle: http://jsfiddle.net/atomicpages/hYVce/

Attribute Selectors

Some of you may be scratching your heads wondering what attributes even are. Let's take a look, shall we?

<ol attribute="value">&nbsp;</ol>

Amazingly enough, attributes can be whatever we want them to be. For example, here is a sample like button using the facebook JavaScript SDK:

<div class="fb-like" data-href="http://example.com/" data-send="false" data-layout="box_count" data-width="50" data-show-faces="false"></div>

data-href, data-send, data-layout, class, data-width, and data-show-faces are all attributes and the text enclosed in double quotes (since we follow the W3C specifications) are called values.

Now that we are (re)acquainted with HTML attributes, let's begin! In CSS we have different specifications that we can use. With attribute selectors we have two specifications we can follow: CSS2 and CSS3. We must be aware of which specification we are using for browser compatibility purposes.

CSS2 Specification

This is best described in a table:

Selector Definition Example - HTML
input[rel] Match the element with "type" attribute <input rel="text">
input[type="text"] Match an element whose "type" attribute value is exactly equal to "text" <input type="text">
input[class~="text"] Match an element whose "class" attribute value is a list of whitespace-separated values, one of which is exactly equal to "text" <input type="text" class="field text">
input[lang|="en"] Match an element whose "lang" attribute has a hyphen-separated list of values beginning (from the left) with "en" <input type="text" lang="en-US">
CSS3 Specification

Being that these are CSS 3 specifications, it means that older browsers may not support them i.e. IE 6-8 and others.
The interesting thing about level 3 attribute selectors is that they're called substring selectors 1

Selector Definition Example - HTML
a[href=^="https"] Match an element whose "href" attribute begins with "https" <a href="https://google.com">Google!</a>
a[href$="sample"] Match an element whose "href" attribute ends with "sample" <a href="http://www.atomicpages.net/blog/sample">Blog!</a>
a[href*="pages"] Match an element whose "href" attribute value contains the substring "pages" <a href="http://www.atomicpages.net/">Home!</a>

To see a real-world example of using these selectors, check out this fiddle: http://jsfiddle.net/atomicpages/jLjfe/

1 http://www.w3.org/TR/css3-selectors/#attribute-selectors

:nth-child Selectors

A new feature to the CSS3 specification, this selectors gives us the power to select and style any element with a parent. We follow a simple equation when using this selection: an+b. This reminds me of high school algebra class when I was trying to get pencils stuck in the ceiling instead of actually paying attention — oh, right...

The first part of our equation, an is asking which element to select. n is the element in question. For those who are familiar with arrays and array indexes, we can think of n as the key value in an array:

$array = array(
	0 => 'Zero',
	1 => 'One',
	2 => 'Two',
	3 => 'Three'
);

Here is some sample HTML

This is some text... <!-- n = 0 -->
This is some text... <!-- n = 1 -->
This is some text... <!-- n = 2 -->
This is some text... <!-- n = 3 -->

In the example above, we show the values of n in the comments. What about a in our equation? Just like the distributive property says in algebra, we need to distribute a to n.

Let's say we want to style only the third p element in the sample of html above. Let's write some code!

p:nth-child(3n) { color: red; }

The above might be your natural inclination for this to be a success. Given the number of elements we have, you would see a correct result. Here is how it's wrong. 3n translates to:

3 * 0 = 0 no style
3 * 1 = 3 red
3 * 2 = 6 red
3 * 3 = 9 red

The correct way to style ONLY the third element would be:

p:nth-child(3) { color: red; }

In this case we just provide the value for n and the rest of the equation is assumed as 1n + 0.

What if we wanted to style all of the EVEN or ODD elements?

p:nth-child(2n+1) { color: red; } /* style odds */
p:nth-child(2n+2) { color: blue; } /* style evens */

Here's the math spelled out:

Odd Even
(2 * 0) + 1 = 1 (2 * 0) + 2 = 2
(2 * 1) + 1 = 3 (2 * 1) + 2 = 4
(2 * 2) + 1 = 5 (2 * 3) + 2 = 6

Some of you may be having an "ah-hah" moment right now and that's quite all right! Here is a more simple way to accomplish the above:

p:nth-child(odd) { color: red; } /* same as 2n + 1 */
p:nth-child(even) { color: blue; } /* same as 2n + 2 */

Finally, as a last example, let's say we wanted to style the 9th, 19th, and 29th element:

p:nth-child(10n-1) { color: green; }
p:nth-child(10n+9) { color: green; }

So which is the correct answer? They're both correct actually. The last bit to our equation, b can be any positive, negative, or zero value – no decimals, ± characters, +-, or -+ allowed. Here is a fiddle to play with! http://jsfiddle.net/atomicpages/fKYmF/.

Basics of CSS Revisited

2

After awhile of going back and re-reading the previous CSS tutorials, I realized there was some flaws here and there and some things that should have been covered earlier but were not. So we're going to start anew with a whole new CSS series that contains CSS2.1, CSS3 and HTML5 (including various hacks for webkit-based browsers, IE, FF, and Opera). Shall we begin?

This tutorial is the absolute basics of CSS and aimed at those that would like to learn about CSS but already have an understanding of HTML.

CSS isn't a web markup language like HTML, XHTML, MathML and so on. CSS is a Cascading Style Sheet and is the backbone for styling web pages. CSS assumes that are you already have prior knowledge of HTML and understand how HTML works so it is critical that an understanding of HTML is present.

What and Why CSS?

Perhaps one might find themselves asking, "what is CSS and why do we need it?" The answer lies in technology. Perhaps you have made a website before using tables in HTML. Yes, this works but it is, however, deprecated (meaning it's not generally practiced any more). Websites composed of HTML tables are a thing of the past because we now have rich client-side applications and complex server-side applications acting as blogging software, content management systems and online stores. Without CSS, these applications would be extremely difficult to update and maintain.

How to CSS?

Luckily for us, CSS is pretty straight forward and easy to learn! Let us get started with the basics!

CSS has the following structure:

selector {property:value;} single-line statement
selector {                  multi-line statement
     property:value;
     property:value;
}

Both examples follow the same general format. We have our selector, property and value.

  • Selector - Is the part of the CSS that is used to specify what to style
  • Property - Is the part of the CSS that states which method should be used to style the Selector
  • Value - Is the part of the CSS that states how much to style or how specifically to style the Selector

Selectors

Selectors can have three different basic forms:

  • HTML (Type) Selectors - "Global" Styles that apply to specific HTML elements
  • Class Selectors - Can be used multiple times on a web page
  • ID Selectors - Mostly used to indicate major sections of a web page

Note: Neither the Class or ID selector can start with a number or a special character, A-Z,a-z only for the first character!

.1bad-selector {property:value;}
.!bad-selector {property:value;}
.good-selector {property:value;}

#1bad-selector {property:value;}
#!bad-selector {property:value;}
#good-selector {property:value;}

HTML selectors, otherwise known as by Type selectors, are literally just HTML tags without angled brackets. For example,

a {
     color:#ff9300; Controls color of anchor element
    text-decoration:underline; controls how the text appears for the anchor
}

"a" represents it html tag to style, that is, <a href="#">Link</a> e.g. This is a link.

That link entitled, "This is a link" has two different properties that are controlling the behavior of the link. One property is controlling the color and a separate property is controlling how the text appears. For example:

We have a link here. The code that makes this link work is like the following CSS:

a {
     color:#0071BB;
     text-decoration:unerline;
}

We have our color (color:#0071BB) and we have the underline (text-decoration:unerline;).

We are choosing to type the a tag. We are changing the default color of the anchor and we are changing how the anchor will appear on a page by adding an underline to the anchor.

A breakdown of this would reveal the following relationship: Selector > Property > Value
The selector relies on the property and value to change how the selector will look.

Another example using HTML selectors would be the following:

ul {
     list-style-type:disc;
     padding-left:20px;
}

ul li {
     float:left;
     margin-left:10px;
}

ul li a {
     padding:5px 10px;
     background-color:black;
     color:white;
}

The CSS above styles the HTML below:

<ul>
     <li><a href="#">Item 1</a></li>
     <li><a href="#">Item 1</a></li>
     <li><a href="#">Item 1</a></li>
</ul>

Although this example is a little longer and contains more code, there is still the relationship between the selectors, properties, and values. We still are choosing which HTML elements to style and we are using properties and values to style them.

Class Selectors

Class selectors are different than HTML selectors. We can use class selectors multiple times on a web page. Class selectors can be used on any HTML element that allows for the use of the class attribute in HTML. Class selectors are detonated by an end stop (.) before the name of the selector.

For instance,

<ul>
     <li class="active"><a href="#">Item 1</a></li>
     <li><a href="#">Item 2</a></li>
     <li><a href="#">Item 3</a></li>
     <li><a href="#">Item 4</a></li>
</ul>
/*"Global" Styles*/
ul {
     list-style-type:disc;
     padding-left:20px;
}

ul li {
     float:left;
     margin-left:10px;
}

ul li a {
     padding:5px 10px;
     background-color:black;
     color:white;
}

/*Class Selector*/

.active {
     padding:5px 10px;
     background-color:black;
     color:white;
}

On the first li element we have <li class="active">. The class attribute is looking for the class selector named "active" and applying those styles to that element. We will discuss class selectors in greater detail in a later tutorial. The main idea for now is that they can be used multiple times in a web page and the selector can be called by using the "class" attribute on virtually any HTML element.

ID Selectors

ID selectors are traditionally used to indicate the major divisions between markup and are mostly used on div (or other block-level element) tags. ID selectors are denotated by the use of a pound (#) symbol.
For example:

<div id="header">
     <div id="nav">
          <ul>
               <li><a href="#">Item 1</a></li>
               <li><a href="#">Item 2</a></li>
               <li><a href="#">Item 3</a></li>
               <li><a href="#">Item 4</a></li>
          </ul>
     </div>
</div>
<div id="sidebar">
     <h2>Joe Smith</h2>
     <ul>
          <li><a href="#">Item 1</a></li>
          <li><a href="#">Item 2</a></li>
          <li><a href="#">Item 3</a></li>
     </ul>
</div>
<div id="content">
     <p>Some text here</p>
</div>
<div class="clearfix"></div>
<div id="footer">
     <p>Copyright &copy; AtomicPages.net 2010. All Rights Reserved.</p>
</div>
body {
     margin:0 auto;
     width:1000px;
     font:11px sans-serif;
     color:#fff;
}

.clearfix {clear:both;}

#header {
     margin:0 auto;
     display:block;
}

#nav {display:table;}
#nav ul {list-style-type:none;}
#nav ul li {
     float:left;
     padding-left:8px;
}

#sidebar {
     width:200px;
     float:left;
}

#content {
     width:800px;
     float:right;
}

#footer {display:table;}

Notice how the ID attribute for HTML works the same way as the class attribute. The ID attribute calls for the id selector with the given name and applies the styles to it. The <div id="nav">, for instance, is calling for the id selector names nav and applying the styles to it. The divs and the ids are also creating logical divisions on our web page e.g. header, nav[igation], sidebar, content and footer.

Comments

Comments are essential to creating any website or program. This allows us to understand what we are thinking or to make additional notes on a web page or program. This also allows for other people to easily see what we our intent is without having to guess.

CSS comments are similar to most multi-line comments in PHP and other programming languages.

/*This is a single line comment*/
/*
*This document was created by AtomicPages.net
*/
body {
     margin:0 auto; /*sets top + bottom margin to 0 and left + right margins to auto*/
     width:1000px;
     font:11px sans-serif; /*keep sans-serif for continuity across the site*/
     color:#fff; /*do NOT change this value!!*/
}

Comments are useful for making annotations for programmers who don't deal with the design of website very much, making your code easier to understand, and giving yourself or whoever created the style sheet credit!

Think you got it? Take the quiz and find out!


CSS Attribute Selectors

0

CSS Attribute selectors are used to select specific attributes in HTML. For example,

<body>
     <h2 class="title">Welcome!</h2>
     <p class="foo" rel="newText">Some text here</p>
</body>

We have two class attributes and on rel attribute labeled, "newText". We could use the attribute selector like the following:

.title {font-size:2em;}
.foo {color:#ccc;}

p[rel=newText] { /*attribute selector*/
     font-size:1.15em;
     font-style:italic;
}

Using this rel attribute and stating what its value is, we can add styles to that exact element even though it has other inherited styles.

Breakdown

Attribute selectors can be somewhat strange at first. But fret not! They're quite easy to learn and can be useful in tricky situations.

[attrib=value]

This means the attribute will equals a certain value. For example:

<div id="form">
     <form action="process.php" method="post">
          <input class="button" type="button" name="button" 
value="Click Me" />
     </form>
</div>

Since this button already has a class attribute, it's already being styled independently. For the sake of argument, let us assume this button is used multiple times on a website and it would be a pain for us to add a new class value. We could simply use an attribute selector to style the button with the value of "Click Me!".

input.button {
     padding:3px;
     background:#3b3b3b url(images/button.png) repeat-x;
     width:50px;
     height:25px;
     color:#ccc;
}

input.button[value=Click Me] {
     background:#4c4c4c url(images/new-button.png) repeat-x;
     color:#999;
}

We have our class called "button" which is styled a certain way. Assuming it was a pain for us to create a new class, we can have the attribute selector get the exact value of "Click Me" and then style it differently.

[attrib*=value]

This one is a little bit more strange. The "*" in this situation kind of acts as a wildcard. This "*=" will search for the the following value anywhere in the attribute value. For example:

<h3 rel="foobarfoo">Text here</h3>

Using this attribute selector we could do the following:

h3[rel*=bar] {
     text-shadow:1px 1px 1px #000;
     color:#fff1d8;
}

This will search the attribute for the word bar and add the styles you want to it. We can also look at this from a different angle:

<div class="item1">Content here</div>
<div class="item_2">Content here</div>
<div class="item-3">Content here</div>

This would be considered poor coding on any level. But let us assume there was a situation like this and you wanted to create a style that would apply to all three of these class selectors. Instead of editing each one individually, we could do the following:

div[class*=post] {font-family:monospace;}

[attrib^=value]

This allows us to choose an attribute based on how it starts. If we have several attributes that start with the same string of text with multiple id and class styles added to the elements already, this can make our life easier.

<div class="foo bar" rel="hello-world">Content Here</div>
<div id="world" class="foo">
     <ul class="bar" rel="hello-world">
          <li>Item</li>
          <li>Item</li>
          <li>Item</li>
          <li rel="hello-world">Item</li>
     <ul>

With a little CSS...

*[rel^=hello-world] {font-style:italic;}

Note: The * in this instance is a wildcard which will automatically put whatever element the attribute and value applies to.

Here is an alternative example:

<a href="http://www.atomicpages.net/blog/2010/05/04/css3-opacity/">CSS3 Opacity</a>
<a href="http://www.atomicpages.net/blog/2010/04/09/mmf2-beginning-video-tutorial-series/">MMF2 Tutorial Series</a>
<a href="http://www.w3.org/standards/xml/core">W3C XML Info</a>
<a href="http://www.whatwg.org/">WHATWG</a>
a[href^=http://www.aomicpages.net/] {color:#ff9300;}

[attrib$=value]

This will search for the value but at the end of the string.

<div class="foo bar">
<!--content here-->
</div>

<div class="bar"></div>
<div class="foo"></div>
div[class$=bar] {text-decoration:underline;}

[attrib~=value]

A typical HTML element that has multiple classes styling it would look like the following:

<div class="foo bar"></div>

Notice that the values are separated by a space. What if we had a different attribute that had multiple values that were separated by a space? Could we use *=? Probably, but the issue with *= is that it can be too picky since this does not require spaces. For example,

<div class="red" rel="foo bar"></div>
div.red {color:red;}
div[rel~=foo] {color:#470b0b;}

Using ~= would require the attribute to be separated by spaces if there were multiple values.

[attrib|=value]

This attribute selector allows us to styles attribute values separated by a dash. This is an alternative to using *=. See the following code:

<div class="blue" rel="bar-foo-bar"></div>
div.blue {background-color:blue;}
div[rel|=bar] {background-color:rgba(50, 50, 50, 0.6);}

Multiple Attribute Selectors

We can use multiple attribute selectors if we want. Consider the following code:

<div title="AtomicPages Blog" rel="example-link" class="blog img">&nbsp;</div>
div[title=AtomicPages Blog][rel|=link] {color:#ccc;}

Basics of CSS - Part #10

0

Today we're going to talk about tables and how they can look significantly better when we add a little bit of CSS to them. If you need a quick refresher on tables, please click here.

Styling Tables

As mentioned above, styling tables is very useful and can instantly make a webpage come to life. The HTML default table is like the following:

Item 1 Item 2
Item 1 Item 2
Item 1 Item 2

Pretty boring if you ask me. Notice how the table has a background of transparent so it will take the color of any background element. The table has that border by default and it definitely could use some tweaking to make it look better.

We're going to use some key properties:

  • border-collapse
  • border

The border property allows us to style all four corners of a border at once, or each side individually. There are no arbitrary shapes with borders. All elements have a clearly defined left, right, bottom, and top side to the element.

border property

Notice how the square has an irregular shape and doesn't appear to be a conventional square. We would call this a diamond shape or something along those lines. It's actually a perfect square that was rotated 45° on a canvas. Notice how the diamond has a background since it is an image and that background has four sides: top, right, bottom, and left.

To see the border tutorial click here

Now that we have a firm understanding and we have refreshed our minds on the border property, we can fully style our tables!

If we add a little bit of CSS and tweak the table to our liking then it could very well look like this:

Item 1 Item 2
Item 1 Item 2
Item 1 Item 2

Although this dives into the world of pseudo-classes, which is discussed in the advanced css tutorial series, we know what our tables can potentially look like with a little bit of work.

Styling

Consider the following code:

table, td {border:1px solid #ff9300;}

This code would add a 1px border that is solid with the color #ff9300 (AtomicPages Orange) around the table and td (table cell) elements. The reason why we chose these elements is because the tr (table row) element does not have a border around it be default. (Usually applying a border color to a table would only mean applying it to the table element only and not the td element.)

This code will outline the table and td elements with a border that is 1px in width, that is solid and the color #ff9300. This can be useful if you want to quickly style a table quickly and easily.

Item 1 Item 2
Item 1 Item 2
Item 1 Item 2

border-collapse

The border-collapse property is a very useful property that collapses the default double border into a single border. For example:

table {
     border-collapse:collapse;
     border:1px solid #ff9300;
}
Item 1 Item 2
Item 1 Item 2
Item 1 Item 2

Notice how the border collapse property instantly gives the table a sharper and less "busy" look. The default border around the table and td elements ceases to exist and we are given a sharper look.

With a little padding (for spacing) for the td elements we can easily space out the table like the following:

th, td {padding:3px;}
/*use as an alternative for cellpadding*/
Item 1 Item 2
Item 1 Item 2
Item 1 Item 2

Using that same principle, we can apply background images and colors to the table, tr, th, and/or the td elements.

For example:

table {
     border-collapse:collapse;
     border:1px solid #ccc;
     background-color:#dbdbdb;
}
Item 1 Item 2
Item 1 Item 2
Item 1 Item 2

We've seen how tables can look and we know what they look like by default — boring. Styling tables can be a great addition to any website whether it is made from tables itself or from a tableless markup using CSS.

Styling Tables
Styling Tables
Size: 8.36 kB

CSS3 Opacity

0

The Opacity Property is slightly different then RGBA and HSLA which was discussed in CSS3 Colors.

Opacity v. RGBA & HSLA

Indeed RGBA has the addition of the "alpha" or opacity value like so:

{code type=css}
background-color:rgba(127, 60, 87, 0.4);
background-color:hsla(68, 100%, 50%, 0.8);
{/code}

Either of these examples will have a color that is opaque in some fashion. Consider the following:

If you're using IE see below:

{code type=css}
background-color:rgba(0, 0, 255, 1);
background-color:rgba(0, 0, 255, 0.8);
background-color:rgba(0, 0, 255, 0.6);
background-color:rgba(0, 0, 255, 0.4);
background-color:rgba(0, 0, 255, 0.2);
{/code}

This code using rgba allows us to create our desired effect.

Allows us to use these opaque colors, however, we can reach the same effect using the standard rgb color space or by using hexadecimal values.

Consider the following example:

We have the same effect using slightly different code in fact. We used the opacity property to create the fading squares.

{code type=css}
background-color:rgb(0, 0, 255); opacity:1.0;
background-color:rgb(0, 0, 255); opacity:0.8;
background-color:rgb(0, 0, 255); opacity:0.6;
background-color:rgb(0, 0, 255); opacity:0.4;
background-color:rgb(0, 0, 255); opacity:0.2;
{/code}

Main difference

The main difference between rgba + hsla and opacity is that we can apply opacity to any element we want instead of just backgrounds. This includes, but is not limited to, images and text.

This is some more text

As we can see, the text is fading with word. The first word is at 100% opacity, the second at 80%, third at 60%, etc... We denote these values in terms of decimals so 1 = 100%, 0.8 = 80%, etc...

Opacity

One really great thing about the opacity property is that you don't need to create an image sprite if you want an image to be slightly translucent before roll over and fully opaque during roll over. Here is an example of opacity:

Chrome

{code type=css}
.chrome-opacity {
background:url (images/chrome.png) center center no-repeat;
height:64px;
width:64px;
opacity:0.8;
}

.chrome-opacity:hover {
background:url (images/chrome.png) center center no-repeat;
height:64px;
width:64px;
opacity:1.0;
}
{/code}

Using method above allows us to easily create semi-opaque images or text and allow them to become fully opaque on roll over or vice versa.

Note: IE 6 only supports the :hover pseudo-class on <a> tags only. Also, IE does not natively support this property where all of the other major browsers do.

To use this property with IE we'll need to create a conditional comment for all versions of IE like the following:

{code type=html}

{/code}

Note: that IE 6 and 7 do NOT extend support to the pseudo-class :hover on anything but <a> tags and therefore the hover will not work.

If you want to see working examples of the opacity property then please download the file!

opacity.zip
opacity.zip
Size: 170.97 KB
Go to Top