Home Using HTML Using CSS Using JS Management Dev Environ Resources

Using CSS

This page defines the Cascading stylesheet Language, better known as CSS, which is the programming language that controls the presentation of HTML elements used when creating a website. The list of topics that are covered include:

  1. What is CSS?
  2. CSS Snytax
  3. The Cascade, Inheritance and Specificity
  4. Debugging and Optimizing CSS
  5. Layout
  6. General Styles
  7. Advanced Styles

Examples will be provided throughout the page in the form of contextual links or <code> references. Perhaps more valuable is the curated list of resources (coming soon). Now that we have a gameplan, lets look at how to write CSS.


What is CSS?

Cascading stylesheets (CSS) is a stylesheet language used to describe the rendering of elements on an HTML document. In the same fashion that HTML has a standardized set of specifications, the W3C group is also the leading authority of CSS best practices. Mozilla and W3Schools, however, are great sources of reference that offer a suite of articles, tutorials and tools for implementing CSS.

The setup for applying CSS to a web page using CSS is quite simple and begins by creating a file with the extension .css then including that file in the <head> of the HTML document that you want to style as a <link>. The <link> tag requires three attributes to be effectively implemented with an HTML document. Those attributes include the href="val", rel="val" and the type="val" attributes.

Strategy to Link a CSS File with an HTML Document
CSS <Link> Strategy

The href="val" attribute specifies the location of an external resource and that resource will always be an external stylesheet whose location is referenced on the same server as the webpage that contains it. This attribute accepts a URL as its value to establish a connection with an external stylesheet. While an external stylesheet is the file that is linked to the HTML document, the precise value for this element is the stylesheets' URL, or Uniform Resource Locator, which is the web browser mechanism used to retrieve a unique resource located on the web.

Authored stylesheets have a relative URL, which is an implicit reference to a resource located on the same server as the web page. However, some resources are located somewhere else in the webiverse and these have an absolute URL, which is an explicitly specified web address. Where a relative URL requires a simple file path to process a file, an absolute URL takes the following format: protocol://domain/path/resource.

Here, protocol specifies how the resource is to be accessed while the domain specifies the name of the computer where the resource is located. The path specifies the sequence of directories leading to the target while the resource, if included, is the target, typically the name of a file. The protocol identifier is either http or https, and is separated from the domain by a colon and two forward slashes. While the protocol is a method for exchanging or transferring data around a computer network, the domain is the server that is being requested. While it is clear that developers should use relative URLs to server style sheets, an argument can be made for using an absolute URL instead. Learn more about URLs and how they formally came about via the RFC 1738 pact.

The rel="val" attribute specifies the relationship of the target object to the link object and can accept a dozen values to specify a particular relationship with the document, but when implementing CSS, its value is always "stylesheet".

The type="val" attribute specifies the Internet media type of the linked resources; a value of "text/css" indicates that the referenced document is an external stylesheet. This attribute is required only when the href="val" attribute is set.

As you can see, setting up a web project to handle CSS is simple, but as the project grows, it will become difficult to manage how styles are applied. A good practice here is to separate project styles from one another using multiple <link> tags in order to prevent spaghetti code. This occurs when you have different layout styles or patterns applied to various elements across multiple pages.

With that covered, lets focus on writing CSS!


CSS Syntax

In life, there are rules: when you follow the rules, you are rewarded and when you break a rule, well, all hell breaks loose. Same analogy applies to CSS: there are rules for writing CSS to instruct a document to display a certain way. CSS is created by employing a rule-set, which is a rule for how the browser will interpret styling an HTML element. A rule-set is simply a block of code that consists of a selector, which references the HTML element that you want to apply styles to, and a declaration, which sets the property and value for the applied style. The terms rule-set, declaration and statement can be used interchangeably.

Selectors are used to select elements based on their name, class, id or attribute. Declarations have beginning and ending curly braces and are composed of a property and corresponding value. A property is an identifier for an HTML attribute that indicates which stylistic features to implement while its value are specifications for how you want those stylistic features. A colon separates the property from its value while a semi-colon separates declarations from one another. With more than 300 CSS properties, the number of styling possibilities is endless!

Selector Types

There are seven types of selectors, all of which are used for a specific purpose. An explanation for how to use selectors appropriately can be found here, here and here.

The element selector element {prop: val;} will apply consistent styles to a specific HTML element. In the example below, all <h1> headings are modified to accept a 'grey' color and 'increased' size.

Example of how to Style the #ID Selector
Example of an Element Selector

The descendant selector element1 element2 {prop: val;} is useful for applying styles to a nested element. In the example below, the <li> within the <ul> will accept a 'grey' color and 'decreased' size.

Example of how to Style the Descendant Selector
Example of a descendant Selector

The child selector element1 > element2 {prop: val;} applies styles to an elements in the event that it is the direct child of that element. In the example below, the declaration renders all <li> elements within a <ol> as green.

Example of how to Style the Child Selector
Example of a child Selector

The .class selector .class {prop: val;} selects elements with a specific class, and can be applied to more than one element.

Example of how to Style the .CLASS Selector
Example of a .CLASS Selector applied to HTML

The illustration above highlights the simplicity in applying a <.class> to an HTML element while the illustration below indicates the style change and how it is applied. In this example, the first declaration will render elements that contain a .class selector as 'red' whereas the second declaration will render <p> elements that contain a .class selector as 'yellow.'

Example of how to Style the .CLASS Selector
Examples of .CLASS Selectors applied in CSS

The #id selector #id {prop: val;} is a unique CSS identifier that can only be used on one element. Whereas the element selector is the most commonly used for applying styles to the same element, the #id selector has the highest level of specificity among all selectors. It is very useful when referencing the location of a block of code, being the only purpose of which I employ this selector.

Example of how to Style the #ID Selector
Example of an #id Selector

In the example above, an #id selector is applied to the navigational links' <a href="#val"> attribute that, when clicked, will transport the user to the <div> with the corresponding id"val". Notice the placement of the hashtag (#); it is always placed in an <a> tag, but not with the targeted element.


The universal selector * {prop: val;} is used to render a specific style to all elements of a website. In the illustration below, all text elements will render 'blue.'

Example of how to Style the Universal Selector
Example of an Universal Selector

One must be careful when using this selector for certain properties as it severly limits application of the same property applied to a different selector. For example, all <a href="val"> have a default style where <link> elements render 'blue' in color. The rule-set above would cause havoc as it would be difficult to differentiate normal text from an <a> element embedded within a block of text.


Pseudo-class selector :pseudo-class {prop: val;} are actually keywords that are added to other selectors and provide a unique style during a particular instance of that selector. Knowing how to apply a pseudo-class will seem difficult at first, but developers become familiar with these quickly as it provides additional styling capabilities. The illustration below highlights ways in which these selectors can be applied to navigational links.

Example of how to Style a Pseudo-Class Selector
Example of a Pseudo-Class Selector

It would be wise to check out this handy almanac of pseudo-class selectors to better understand how these can be applied in a variety of situations, one of which is a pseudo-class based on position, which is a good method for specifiying a location for blocks of code. In this regard, understanding how to use and test the :nth-child(), which selects elements based on an algebraic expression, is imperative, but that should not stop one from exploring :required(), :focus and :disabled pseudo-class selectors that go far when styling <form>inputs.


In contrast to pseudo-class selectors, pseudo-element selector can be used to style a specific part of an element. There are many amazing ways to use pseudo-elements, but the scope of this subject focuses on four selectors that adds depth to elements that possess text.

The :first-letter and :first-line pseudo-elements can be used to add style to the first letter or first line of text, respectively, but they can only be applied to block-level elements. In the illustration below, the first declaration states that the 'first letter' of 'every paragraph' with a class of 'intro' will display as 'red.' The second declaration states that the 'first line' of 'every paragraph' with a class of 'intro' will display 'bolder' than the text below it.

Example of how to Style a Pseudo-Element Selector
Example of a Pseudo-Element Selector

The ::before and ::after pseudo-elements can be used to add content before or after an element, respectively. The key to these selectors is that they require the content: ""; property in order to work. Add a symbol as a value for the property, or leave it empty and add the background shorthand property to the declaration with the resource (i.e. URL, image, string) that you want to display. In the illustration below, the value of the content: ""; property will display a checkmark before any list-item.

Example of how to Style a Pseudo-Element Selector
Example of a Pseudo-Element Selector

These selector types can do more than improve how text is displayed: they can even be used to create multiple backgrounds and borders.


The attribute selector element[attribute = "val" {prop: val;} is used to apply styles to an HTML element with a specific attribute, but what do I know: I never use this selector! If I did, I would probably use it to select all <p> elements with a lang attribute that has a value of zh, for the Mandarin language. But what would I use that for!?!

Example of how to Style the Attribute Selector
Example of an Attribute Selector

Again, learning to use these selectors is a challenge every developer encounters. One thing to remember is that sometimes combinator selectors can be more efficient than creating separate styles for each targeted element. Equally important is to know how to hide styles when in production-mode. We implement comments by adding /* and */ to the beginning and end of any text; this will prevent any code from being rendered by the browser. Comments are also useful when collaborating on a project to ensure that all team members can readily comprehend its working status.


The Cascade, Inheritance & Specificity

The core of CSS is the Cascade, an algorithm that defines how to combine property values that originate from different sources. Essentially, it defines that the order of CSS rules is important, and when not followed, could produce disastrous results. In accordance with the rules, developers should be wary of the descending order of importance for the cascade: origin, specificity and order.

The order in which CSS declarations cascade depends on the origin of CSS declarations. Because style sheets come from different origins, they tend to overlap in scope, and this is when the algorithm defines the interaction. The browser uses a basic style sheet known as a user-agent stylesheet that provides a default style to any document. A user stylesheet is created by individual users to customize and override styles that have been applied to the browser, regardless of origin. Authored stylesheets are CSS files created by developers to define how a website will display. Respectively, these origins represent the order of priority in which they cascade, top-down, meaning that a user-agent stylesheet will take precedence over an authored stylesheet.

In the event that multiple declarations target one specific element, specificity is invoked, which are actions taken by browsers to determine which CSS declaration should be applied. Generally, the last declaration made based on multiple declarations of equal specificity will be applied to the CSS. In the illustration below, the color of the class .fav will render 'black' because the source order determines which declaration to utilize.

Specificity Exemplified
Example of Specifity at Work

The amount of specificity possessed by selectors can alter such measurement, which is why calculating specificity values can be challenging. The basic principle of specificity defines a rank-order of most to least significant selectors to use when writing CSS. #id selectors have the highest rank followed by .class, [attribute = "val"], :pseudo-class, <element> then finally the ::pseudo-element.

It should be mentioned that the universal selector [ * ], selector combinators [ +, >, ~, '', || ] and the negation pseudo-class [ :not() ]do not impair specificity. The !important exemption [ ! ], as well as an inline-style, can be used to override any declaration, but it is considered bad practice due to the complications that can arise with debugging. There are plenty of tools readily available online to help developers better understand this concept.

CSS styles are also controlled via inheritance, which is the concept that some property values applied to an element will be inherited by its children, but some will not. A good example is a <p> tag nested in a <div>; setting the color property for the <div> will cause the <p> to be the same color. Setting the color property for the <p> will override the styles applied to the <div>. Developers should consult a CSS property reference list to ascertain which properties are natively inherited.


Debugging CSS

There are times when developers write declarations that are not rendered in the browser, and a simple explanation would target a syntax error as the culprit. When this happens, the browser will simply ignore the rule. If this happens, developers will have to resolve the conflict independently, and this sometimes creates headaches. Luckily, there are plenty of resources available to help debug CSS.

Major internet browsers –Chrome, Firefox, Microsoft Edge and Safari, all offer dev tools to help troubleshoot CSS issues. These toolkits employ an element inspector, a styles panel and a mode for responsive debugging that allows developers to understand where styling conflicts exist. When inspecting styles, it is important to note the declarations that are crossed out or have a warning icon, for example, have been overridden or are invalid. Thus, such elements should be the focus for trying to alleviate any style concerns. Learn more about Chrome, Firefox, Microsoft Edge and Safari dev tools.

A simpler way to parse code for potential errors would be to use a linter, which searches for invalid declarations, specificity, and duplicate or unused selectors in an effort to sanitize code of any unnecessary elements. The W3C group has a quality online validator.

There are additional methods that developers can take to optimize a web site and minifying files is a good first step. Minification is the process of removing unnecessary characters from the file in order to improve the files efficiency by decreasing the size of the file.

Above all else, developers can best serve themselves by refactoring their code. Refactoring is the process of organizing code as most efficiently as possible; enhancing readability affords faster code execution, which is the ultimate goal here. When reorganizing code, it is a good practice to subscribe to a specific style guide with criteria that concentrates on declaration order, formatting rules and use of unit-values that you want to use. Employing a Block Element Modifier (BEM) naming convention would provide a more consistent code structure for code sharing in front-end development. Learn more about BEM.


General Styles

Font Properties

The font CSS Property allows developers to modify how text is displayed. This property can be used to set the elements font to the systems font or as a shorthand for setting multiple font-property Values. There are nearly a dozen distinctive font-property features that can be used for styling. I categorically understand such properties to either modify the style or spacing of text.

Font-Family

The font-family CSS property is used to set system fonts by specifying a prioritized list of font-family names, which are separated by a comma, for the selected element. When the font name has two names, that font name must be enclosed with quotation marks. Moreover, adding a second parameter for this property is required; serif or sans-serif are your fallback options. The examples below illustrate how to plan your font-family:

font-family: Georgia, serif;
font-family: "Gill Sans", sans-serif;

Sometimes, one font just wont do and in such cases I utilize these two Font-Pairing tools to find a typographic combination that fits my needs. My favorite fonts to work with include Helvetica, Raleway and Roboto.

Font Shorthand

When using font as shorthand, values for font-size and font-family must be included; values for font-style, font-variant, font-weight and line-height (lh) are optional. There is also an order of precedence for how font properties can be used. For starters, font-style, -variant and -weight precede -size. When used, line-height is attached to font-size and font-family (fam) is always the last value specified.

-size / -fam
font: 1.2em "Fira Sans", sans-serif;
-weight / -style / -fam
font: bold italic serif
-variant / -weight / -size & lh / -fam
font: small-caps bold 24px/1 serif;

Again, when using all font properties, the shorthand order includes font-style, -variant, -weight, -size, line-height and font-family.

Font-Size

The font-size CSS property specifies the size of the font using numerical Values. Possible value options include PX, EM, REM, VH and VW

px is an industry standard static value as it is used for pixel accuracy. The em value is a responsive type. Calculate the em equivalent for any px value by dividing the desired element px value by its parent element font-size in pixels. The rem value is an alternative to the em value in that it does not compound as it is relative to the root html element.

I learned how to calculate font-size through trial-and-error and will readily admit that I am horrible at performing math calculations. Heck, I took College Algebra 101...to graduate! There are a lot of resources designed to make sizing a less-stressful experience. Chen Hui-Jing and Zach Leatherman wrote some good articles on using math to calculate font-sizes and typography, respectively. Type Scale is a visual calculator that allows you to preview how different font-size and font-family values would be displayed. The px-em and px-vh conversion tools offer a quick and easy way to convert font-sizes based on the objective.

Font-Weight

The font-weight CSS property specifies the weight or boldness of the text. The font-family will determine how a font-weight is applied, if applied at all. Values for this property include font-weight: normal and bold. There is also a numerical scale between 100-900 that will increase font boldness with each increment (increments of 100).

Font-Variant

The font-variant CSS property contextually modifies font. Useful values for this property include normal and small-caps. The text-transform CSS property works in the same fasion, using values such as uppercase, lowercase or capitalize.

Text Decorations

The text-decoration CSS property specifies the appearance of decorative lines used on text. Useful values that declare how a line is used include none, underline, line-through and blink. Line style options include solid, dashed, dotted and wavy.

This property can also be used as a shorthand for setting multiple text-decoration values in a single declaration, which include text-decoration-line, text-decoration-color, and text-decoration-style with no particular order of precedence.

Text Shadows

The text-shadow CSS property adds shadows to text. It accepts a comma-separated list of shadows to be applied to the text and any of its decorations. Each shadow is described by some combination of X and Y offsets (required) from the element, and blur radius and color (optional).

offset-x | offset-y | blur-radius | color
text-shadow: 1px 1px 2px pink;
color | offset-x | offset-y | blur-radius
text-shadow: #FC0 1px 0 10px;
-x | -y | blur-radius | color [x3 for 3 shadows]
text-shadow: 1px 1px 2px red,
0 0 1em blue, 0 0 0.2em blue;
Line-Height

The line-height CSS property sets the height or amount of space placed between lines. This property uses a value that is a number, length or percentage. I enjoy what 150% and values between 0.8 - 1.5.

Aside from styling font, it is equally important to know how to properly position text. An example of this is the line-height property used above in the font-shortand, which sets the height between sentences. Below are some of the properties I have found helpful to adjust text layout.

Text-Align

The text-align CSS property describes how inline content like text is aligned in its parent block element. This property accepts the values left, right, center or justify which aligns text to the left side, right side, center of box or left and right side.

Text-Indent

The text-indent CSS property specifies the amount of indentation (empty space) that is put before lines of text in a block. By default, this controls the indentation of only the first formatted line of the block. Trusted values that will display a proper indention are 16px, 8% and 1em.

Letter-Spacing

The letter-spacing CSS property specifies the spacing behavior between individual letters. Depending on usage, normal, 0.2em and 4px are trusted values to use when applying this property.

Word-Spacing

The word-spacing CSS property specifies the spacing behavior between individual words. Idea values to use for such cases include 0.2em, 2px and 0.4ch.

Icons

Using icons as font is another practice web developers should be familiar with. Outfits like Font-Awesome and Material Design make including icon fonts into a web project simple.

Last Updated: 3/20/2019