CSS 3 Visual Learning Guide | Part 1 - UX Planet

By Mike Ludo

CSS 3 Visual Learning Guide | Part 1

Mike Ludo

This six-part series fills a gap in the learning and reference works on introductory web design. Instead of the terse definitions written for experts found in online documentation resources, or long commentaries to ease novices into programming, this series strikes a balance between succinct explanation and complete visualizations of code so that the key concepts are learned through easy-to-follow examples. This series details comprehensively the practice of enhancing the visual styling of HTML-structured web content through the use of Cascading Style Sheets, by covering CSS 3 syntax and properties.

What This Series Assumes

This article series assumes a prior knowledge of HTML. If you have worked through the precursor series to this one– HTML 5 Visual Learning Guide– or have equivalent knowledge and skills in using markup for HTML pages, you will be able to work through the CSS examples. No previous experience with CSS is required. Since HTML experience is presumed, it is also expected that you have basic knowledge of how to use a code editor, and how to use an FTP client application if your eventual goal is to design live websites that are stored on a web server. Those topics are also covered in the HTML 5 Visual Learning Guide.

Access the Code Examples

All the code in these articles be downloaded or copied from a Google doc so that you can save a little time typing and follow along with the examples a little faster. However, the more time you spend typing, the better and faster you will learn how to write CSS! The link to all the code used in the following pages is:

http://bit.ly/CSScode

In the Google doc, all the code referenced in the following examples can be quickly found by clicking on its associated tab in the Google doc outline, which is visible on the left side of the screen. Just go to the Google doc section, using the outline to navigate the code content, and paste the pertinent code into your text editor to try it out in your web browser or in an online IDE (integrated development environment) like JSFiddle or Repl.it, or after saving the .html and/or .css text files (linking to an external .css file is discussed shortly).

Use the outline on the left to quickly find the online code examples in the Google doc.

Introduction

HTML, CSS and JavaScript– the languages of the web

Ultimately, to become skilled at creating your own websites from scratch– instead of using a website creator tool or template provided by a web hosting service– where you write the source code text files linked to associated media and other assets yourself, you will need to learn the three main languages of the web:

HTML (hypertext markup language) for organizing and structuring web-based content.

CSS (cascading style sheets) for controlling the visual style and presentation aspects of HTML-structured content.

JavaScript for enhancing web documents with interactivity and making a web browser a general-purpose software platform in its own right.

Usually one learns these languages in the order above, since in doing so the design complexity gradually increases as websites become more sophisticated in their capabilities and richness of the user experience. This series is squarely focused on the visual design aspects of websites, as distinct from their organization and structure, which is the domain of HTML, or the fully featured software application and interaction capabilities, which is the domain of JavaScript or Js for short.

Recommended Code Editors

It is assumed that, since you have some experience with HTML (which is a prerequisite for following along with the examples below), that you can make your way around a code editor. Some popular code editors include:

● Sublime Text

There are also online code editors like JSFiddle that allow you to type code online and see the results. JSFiddle allows you to type HTML, CSS and JavaScript in three different panels, and shows the results in a fourth panel when you run the code. JSFiddle also has a great ‘Tidy’ feature which, with one button press, sorts out the line spacing if you wrote code without being too precise in your indentation discipline! Another great online code editor to consider is Repl.it. Go to

https://repl.it/languages

and choose the language designation “HTML, CSS, JS: The languages that make up the web” and you can do all of your code editing in a browser.

Cascading Styles

The “cascade” that puts the “C” in CSS refers to the idea that you can target many elements on web pages with a minimum amount of coding. Instead of styling each element in an .html document as it appears in the lines of the text file, with CSS you target whole categories of elements for styling which will automatically be applied anywhere the elements appear. In this way a style will ‘cascade’ throughout all the pages and modify the elements targeted with only a few lines of .css. This cascading concept will become clearer as you work through the examples, and you will begin to see how CSS makes it easier to manage site-wide changes in a much more efficient way compared to the early days of web design when HTML elements had to be styled individually. A single external.css file can change the presentation aspects of a complex website comprised of many pages, with each page being a different .html document.

The first “S” in CSS is for “style” which simply means a set of instructions for formatting elements and contents in an HTML document in ways you define explicitly. The second “S” refers perhaps somewhat oddly to a .css file by calling it a ‘sheet,’ which sounds very papery. But a .css file is just a text file that is fundamentally no different from Python .py text files, .html text files, .js JavaScript text files, or .cpp C++ text files. We don’t refer to any of these other kinds of text files that contain source code as ‘sheets!’ The concept of a ‘style sheet’ originated in the publishing industry where they were also called ‘style guides.’ These style guides/style sheets gave formatting instructions for books so that they would be published in accordance with the style standards of the publishing house for particular series or editions. Cascading Style Sheets certainly sounds a lot better than, say, Cascading Style Formatting Instructional Text Files!

CSS 3 is the latest standard in the evolution of cascading style sheets and is considered to be a continuously evolving standard where new features are developed and released on an ongoing basis rather than being saved for a later release of a hypothetical CSS 4 (a similar situation is operative with regards to HTML 5). Earlier versions of CSS were considered to be “monolithic specifications,” but today’s web development culture has adopted a more agile stance towards rolling out technological changes, so rather than expecting that a major release of CSS 4 might be around the corner, get used to the idea instead that CSS 3 is going to be gradually evolving in smaller increments over time.

Syntax

The CSS syntax for creating comments in the style sheet is /* ……. */. Content written inside these characters are ignored by the browser for display purposes and function as a level of content along the lines of “notes to self.” Comments also allow you to temporarily deactivate code blocks so that you can see the effects of the code more clearly when refining a design by deactivating it when comment symbols are placed around it. CSS comments involve fewer characters compared to HTML comments:

/* here is a comment that will be ignored by the browser and so will not display */

Comments in CSS can be written on a single line or be written on multiple lines, called multi-line comments, using the same characters to bracket the commented text.

White Space & Indentations

Like HTML and many programming languages, CSS ignores most instances of white space in your code. Use white space primarily to make your code readable, by yourself and others. When using white spaces to make indentations, which is the standard way for expressing the hierarchical relationships of elements in HTML and declarations in CSS, many web standards recommend two spaces per level of indentation. See, for example, the Google HTML/CSS Style Guide.

The Three Ways to Add CSS to an HTML Document

You may recall from your HTML knowledge that there are three ways to add CSS to an HTML document: as inline style, as an internal style, and as a link to an external stylesheet. In this series, the internal style method will be used because it more easily demonstrates, for learning purposes, how CSS relates to HTML in a single screen window and when using short economical code snippets. However, normally you will want to be using CSS script in external style sheets, since that is the generally preferred method. Also for visual clarity, many redundant elements will be omitted, such as <!DOCTYPE html>, <html> and <body>. Just assume that, if these examples were used on real web pages, you would have all the requisite elements in place.

For review, let’s just remind ourselves of the syntax and method for each manner of adding CSS to an HTML document.

Inline Style

Inline CSS is presented within the opening HTML tag, where style is a Global Attribute that can be used by any HTML element. The value of any applied style attribute is a property:value pairing declared inside of quotation marks, attached to the attribute through the assignment operator equal sign, = . Every property:value pairing should end in a semi-colon, and similarly when combining more than one inline style, each property:value pairing should be separated by a semicolon.

In the early days of the web, before Cascading Style Sheets, a vast amount of work was entailed by having to style every HTML element individually. Any change of a style decided later on meant that each element that had the style had to be manually adjusted. Here’s an example of inline CSS as part of an HTML text file:

<h1 style="color:red; font-style:italic; font-weight:100;">Red Heading Typography</h1>

Above three styles have been applied, making the font color red, its style italic, and the font weight 100 (on a 9-item scale 100 to 900– note that not all fonts support all nine available CSS weights).

Internal Style

With internal CSS, the style is placed inside the <head> section of the HTML document, which is always above the <body> section, you will recall. This method is internal to the HTML document, i.e. a single web page, as a whole, rather than specific to a single element, which is why it is called internal. The CSS is applied within the <style> HTML opening and closing tags instead of a style attribute declaration and is declared in the standard CSS format. The basic CSS syntax is:

s { property : value; property: value;

}

The “s” above stands for “selector”, which is any HTML element (in this context, “s” is not the HTML tag for “strikethrough!”). With internal CSS, the property:value pairs are declared within curly braces, { }, instead of quotation marks. The property:value pairs taken together with the curly braces make up a declaration in CSS. At a high level, the syntactical construct can be understood as:

Selector {Declaration} {Declaration} {Declaration}
Selector {Declaration} {Declaration}

And each declaration in turn is made up of:

{property:value; property:value; property:value;}
{property:value; property:value;}

etc.

A selector and its declaration(s) together make up a rule set:

rule set = selector {declaration(s)}

To ground this syntax in a typical example, let’s look at the use of multiple declarations applied to a single selector. Note that sometimes the order of declarations has no effect on the visual result, but in other cases the order does have an effect, as we will see in later examples.

<style> h2 { text-align: center; font-family: cursive; color: orange; }

</style>

<h2> Hi, I've been styled.

</h2>

Multiple declarations on the <h2> selector.

Instead of the styles being declared one after another on the same line as with inline CSS, with internal CSS each style declaration starts a new line and is completed with a semicolon. It’s considered good practice to always complete a declaration with a semicolon even with the final one, since it’s possible that later on you or another designer may add new styles and not realize that there are missing semicolons above in the code that can cause a bug when rendering the style.

The code below is the internal CSS version of the same style we applied above in the inline example. The CSS is now located inside of curly braces, which are inside of the <style> tags which are inside of the <head> section. The CSS is applied in the head first (before the body) since a browser parses the code in a linear fashion. In this way, the browser does not first load an unstyled version of a page and then get to work restyling it all, which is what would happen if internal CSS was placed at the bottom of the .html file. Rather, the browser obtains the needed style information first in the <head>, then all subsequent HTML content is rendered in the style that was first parsed from the internal style declarations.

<head> <style> h1 { color: red; font-style: italic; font-weight: 100; } </style></head>

<h1>Red Heading Typography</h1>

External Stylesheet

Well-developed styles are made up of many lines of code, and for this reason it is usually impractical to create too many style statements as internal CSS within the <head> area of an .html document. Instead, CSS code is usually placed in its own text file(s) that have the file extension .css. This external style is then linked to in the <head> of an .html document via a <link> element. This link to the external .css file will instruct the browser to obtain the styling information from the external file first before continuing to load, and style, the subsequent HTML content. When using code editors to write CSS les, make sure you set the file’s syntax to CSS, though many editors will automatically detect the language you are writing in. When you save the file, make sure it has the .css file extension so that it is usable as a style sheet for a browser.

<html> <head> <link rel="stylesheet" href="css.css" type="text/css"> </head> <body> </body>

</html>

Above, we define the relationship (the rel attribute in <link>) between the .html document and the external resource as a stylesheet relationship. The URL to locate the external style sheet is a relative URL path– in this example, the CSS file is in the same directory as the index.html document. As your websites become more complex, you will eventually want to have your CSS source code files in their own directories or folders, in which case the URL in the href might instead be “CSS/css.css” or “scripts/css.css” and so on. These forward slashes indicate that the .css file is to be found inside of a directory called “CSS” or “scripts,” and that these directories are in the same directory as the .html file. Finally, the Media Type of the stylesheet is declared with the type attribute. CSS, like all source code, is always just a text file, but instead of the usual .txt file extension used for text files, .css is used so that the browser knows to parse the code as containing styling information.

Placing the .css file in the same directory as the .html file, OR alternately, in a scripts directory. The value of the href attribute has to specify the path needed to find the external style document.

The Basic CSS Syntax

Often the basic CSS syntax will work fine for your needs:

s { property : value; property: value;

}

However, more complex designs require more than the basic syntax. You will typically be needing to style HTML elements that have classes and ids assigned to them, for example. Building on the basic syntax, targeting styles for class and id names looks as follows.

s.class { property : value; property: value;

}

s#id { property : value; property: value;

}

The selector with a period followed by the class name will target styling at the HTML elements that have that class assigned to them, and the selector with a hashtag joining it to an id name will target elements with that id.

The Tree Structure

CSS will reinforce your previous learning of the HTML document’s tree structure, which was discussed in the HTML 5 Visual Learning Guide.

HTML markup as a tree structure.

To target the elements on HTML documents effectively, you will often be specifying with a high degree of granularity the parent-child relationships of HTML tags as they are nested inside each other in hierarchical relationships. In the many examples that follow are various instances of targeting elements based on their hierarchical relationships to each other.

By default, in CSS children will inherit the properties of their parents, just as happens in biology, zoology, genetics, tax codes and web development! You can override this behavior by giving children unique styling of their own to override their parents’ influence. Let’s look at how this works, using an internal <style> example. Below, we have defined the color properties for the parent elements <body> and <ol> (the main content of this HTML page, an ordered list). <body> is a parent element of both <h2> and <ol>. In the <head>, however, following the style for <body> a new style for <ol> has been declared that will override the red style of <body> and replace it with a new style that colors <ol> blue instead. Note, however, that <ol> has no visual presence by itself. It is only the children of <ol>, the list items <li> that inherit the blue property from their parent, <ol>. The red property of the “grandparent” element, <body>, has been replaced by the blue style defined for <ol>.

<head> <style> body { color: red; font-style: italic; font-weight: 100;

}

ol { color: blue; font-style: italic; font-weight: 100; } </style></head><body> <h2>I'm red, too!</h2> <ol> <li>I'm blue, too!</li> <li>I'm blue, too!</li> <li>I'm blue, too!</li> </ol>

</body>

Changing the default inheritance of properties between parents and their children.

So typically in CSS, property values will be inherited from the nearest ancestor element if no other style is declared to style it otherwise.

Hierarchy of Style Declarations

There is a hierarchy in place between the different kinds of style declarations which can be defined as follows:

● The external style sheet defines presentation formatting for a whole website.

● Internal style sheet declarations will override any competing declarations in the external style sheet and apply styles only to the document where the internal style appears.

● An inline style will override both external and internal style declarations and apply a style only to the element in which it has been declared as a style attribute.

So despite the prevalent use of external style sheets to define the presentation aspects of whole websites, there are still many instances when you will want to use internal or inline CSS if you want to make unique stylistic choices on particular pages or elements with internal or inline CSS, respectively.

Specific Beats General

An aspect of the cascading concept to keep foremost in mind as you design your styles is that specific styles always override general styles. For example, an element with an id associated with it as an attribute is more specific than the same element without the id. Thus, a style targeted at an element’s selector#id will override the style applied to the element’s general selector. Similarly, an id is more specific than a class and so will override a class declaration.

● p {declaration} // this styles all <p> elements.

Breaking Ties: Last One Wins

If there are conflicting style declarations and a ‘tie’ emerges when trying to decide which style declaration has the final say over the element’s display, the last declaration in the sequence wins.

p {font-weight: 200}p {font-weight: 800}

p {font-weight: 400}

Result: all <p> elements will have a font-weight of 400, since there is no hierarchy implicit in the contradictory declarations. The last declared style wins, in keeping with the general linear line-by-line, top-to-bottom parsing of source code files by the browser.

!important

You can add the !important rule if you want to assure that a style declaration does not get overridden by other declarations, whether this may be caused by ties, general-to-specific hierarchies, or the linear parsing of lines of CSS relative to prior and subsequent lines. Adding !important after a property:value pair will assure that it takes priority over any other declaration that might potentially conflict with it.

s {property:value !important; property:value;}

Targeting Multiple Elements with the Same Declarations

Often you will want to apply the same style declarations to a collection of elements. To do so, simply list the elements using a comma to separate them.

<style> h1, h2, h3, h4 { color: green; font-weight: 800; font-family: sans-serif; }</style><h2> I have a style in common with other headers.</h2><h3> Me too.</h3><h4> Me three.

</h4>

Using commas to apply the same declaration to multiple HTML elements.

Targeting Nested Elements aka Descendent Selectors

Syntax construct: ol li em {style declaration}

When you want to traverse the tree structure in order to target style declarations to specifically intended children of elements, omit the comma between the list of selectors, and indicate your target by naming it as the final selector. In this example, only the <em> element inside of a <li> that is inside of an <ol> will have the style applied to it:

<style> ol li em { color: red; font-weight: bold; font-family: cursive; }

</style>

<ol> <li>No Emphasis, No Style</li> <li>No Emphasis, No Style</li> <li><em>Have Emphasis, Have Style!</em></li>

</ol>

Omitting commas to traverse the tree structure and target the last descendent selector, which you can also think of as the final child element.

Direct child selector

Sometimes you want a style applied to the direct child of a parent element, rather than all similar elements that may be a descendent of a parent element. For this situation there is the direct child selector, which is a greater than sign > that connects the parent selector to its direct child: article > h2 { ……. }

Let’s compare the difference between the use of a direct child selector, and regular descendent selection shown previously. The two sets of code blocks below are exactly the same, except that one has the direct child selector > and the other omits it, using just a whitespace between parent and child. The rendered result is shown beneath each code block.

<style> article>h2 { color: red; font-weight: bold; font-family: cursive; }

</style>

<article> <h2> Styled heading. </h2> <p> Text of the first article section. </p> <section> <h2> Not styled heading but same heading number. </h2> </section>

</article>

Since the second <h2> element is not a direct child of <article>, but rather is a direct child of <section>, the second <h2> element is not styled. The code below is identical to the example above, with the exception that the direct child selector > is omitted.

<style> article h2 { color: red; font-weight: bold; font-family: cursive; }

</style>

<article> <h2> Styled heading. </h2> <p> Text of the first article section. </p> <section> <h2> Not styled heading but same heading number. </h2> </section>

</article>

Here, both <h2> elements receive the effects of the style declaration, because both are children of <article>. The second <h2> may be more like a ‘grandchild’ of <article> but it is still in a child relation to its parent element. Only the direct child selector > can limit the style to the just one hierarchical level below the indicated parent element.

Pseudo-Classes

Some selectors have states associated with them, an important one being <a> (the link element or anchor tag). These states are known as pseudo-classes, and you indicate the state by using a colon connected to its selector. Unlike many property declarations, the declaration order of pseudo-classes often matters. Below is shown some pseudo-classes associated with <a> elements and the order in which to specify them.

a:link {declaration} a:visited {declaration}a:hover {declaration}

a:active {declaration}

In the later exercises there will be some examples where pseudo-classes are used in the context of illustrating CSS properties, particularly around adding styles to link, i.e. anchor, elements.

Targeting Elements by Attribute

You can target elements by their attributes using a variety of syntactical methods. Since attributes usually have values associated with them, we can use the attribute:value pairing as one way to target style to the elements that have them.

s [attribute=“value”] { …… }

For example, you might use this method for targeting a style is to a particular URL which is the value of an href attribute so that a web address gets styled in a certain way. In the style below, we will define different lang attributes, using the ISO 639–2 two-letter language codes, for three paragraph elements and see the result of the style declarations.

<style> p[lang="fr"] { color: blue; font-weight: bold; font-family: cursive; } p[lang="pl"] { color: red; font-weight: bold; font-family: cursive; }

</style>

<p lang="en">I am in English.</p><p lang="fr">Je suis en français.</p> <!--French -->

<p lang="pl">Jestem po polsku.</p> <!-- Polish -->

Style declarations based on the lang attribute of three <p> elements.

Since some attributes do not take values, we can target these elements just by the attribute name using the construct:

[attribute] { …… }

In the following example, we have a selection of ice cream flavors, but since we are out of Cherry ice cream, its <button> attribute is set to disabled. Thus, this style targets only elements that have the attribute of disabled in a red color, while ice cream flavors that are in stock are colored green.

<style> button { background-color: lightgreen; } [disabled] { background-color: red; color: white;</style> <button type= “submit”>Chocolate</button><br><br><button type= “submit”>Strawberry</button><br><br><button type= “submit”>Vanilla</button><br><br>

<button type= “submit” disabled>Cherry</button><br><br>

Targeting a style by stand alone attribute name. Sorry, out of Cherry.

We can also use the selector bracket syntax, s [ ] , for elements that have attributes without values, or even with values. The style declarations below will render exactly as the code above.

<style> button[type] { background-color: lightgreen; } button[disabled] { background-color: red; color: white;

</style>

Since all of these buttons have the type attribute, we can apply the green style to all of them. However, the one button that has the disabled attribute will have the green style overridden and receive the red style instead.

As it turns out, this happens to also be an example where the order of style declarations does matter. In your code editor, swap the two styles so that the disabled style comes before the type style, and see what happens when you render the result.

But wait, there’s more! More ways to target attributes, that is.

[attr |=value]

To really understand what you can do with the pipe character= syntax, |= , let’s introduce a very interesting online resource called the IANA Language Subtag Registry.

The universal language subtag registry allows web developers to achieve more granularity with defining human languages than is possible with using the two-letter language codes on the ISO 639–1 list. With the ISO standard, English is just ‘en.’ However, language subtags allow us to categorize not just languages, but also regions and scripts. Since the regional subtag for the Bahamas is bs, we can specify the idea of ‘English as spoken in the Bahamas’ as ‘en-bs.’

Using the CSS selector type |= allows us to apply a style either to the value defined, or a value that begins with the value defined, when working with dash-separated lists. This selector type can account for the variations of a value based on what might follow after the hyphen.

<style> [lang|=en] { color: BlueViolet; font-size: 1.5em; font-style: oblique; }</style><p lang="en-bs">English in the Bahamas</p><p lang="fr-bs">French in the Bahamas</p><p lang="es-bs">Spanish in the Bahamas</p><p lang="fr-009">French in Oceania</p><p lang="es">Spanish in Latin America</p>

<p lang="en">Just General English Anywhere</p>

Styling a complete language value, en, or any of its hyphenated variants.

[attr^=value]

The carat= syntax, ^= , is very similar to |= except that instead of seeking the beginning part of values that are comprised of hyphen-separated lists, the beginning part of a value is a complete string of characters. In the example below, there is an intentional CSS syntax mistake, since the CSS asks for ^=english but the last <p> element has the value “English” rather than “english.” Property values are case sensitive, and so ‘english’ is not the same thing as ‘English’ and thus the final element does not receive the styling.

<style> [itemprop^=english] { color: DeepSkyBlue; font-size: 1.5em; font-style: oblique; }</style><p itemprop="english in bahamas">English in the Bahamas</p><p itemprop="english anywhere">Just General English</p><p itemprop="american english">American English</p><p itemprop="british english">British English</p><p itemprop="english on Mars">Martian English</p>

<p itemprop="English on Mars">Uh Oh Watch Your Capitalization</p>

When seeking the first part of a value that is a complete string rather than a dash-separated list, use ^= syntax instead of |=

Value Case Insensitivity

While normally in life we don’t want to be insensitive, sometimes in programming languages we want to declare our code to be intentionally case insensitive, meaning that it will parse the same regardless of whether or not the value is composed of upper- or lower-case characters. For instance, maybe we are fearful that we might have been somewhat inattentive coders in various lines of our source files. We can define CSS selectors to be case insensitive by adding an “i” or its capitalized version, “I’ as the last character of a value, which will make the value ignore case information. Even the fact that we can use upper or lower case i/I shows how case insensitive it is!

One way to fix the CSS above is to simply make our style declaration case insensitive. We can do this just by changing the selector syntax to:

<style> [itemprop^=english i] { color: DeepSkyBlue; font-size: 1.5em; font-style: oblique; }</style><p itemprop="english in bahamas">English in the Bahamas</p><p itemprop="english anywhere">Just General English</p><p itemprop="american english">American English</p><p itemprop="british english">British English</p><p itemprop="english on Mars" style="color:red;">Martian English</p>

<p itemprop="English on Mars">Oh ok, who cares about capitalization, anyway?</p>

i or I as the final character in a selector value makes the style declaration case insensitive.

Also, just to make a visual reference to Mars as the Red Planet, we have added an additional inline CSS style declaration to make the Martian English typeface red, which overrides the internal style at the top of the document. This happens because an inline style is more specific than an internal style, just as internal style overrides an external style, as discussed earlier.

amazon.com/author/mikeludo

End of Part 1

Part 2