# Cascading Style Sheets

## Summary


Web content is structured in HTML. Apart from content, styling is also important. A web designer often wishes to control font style, text size, alignment, page layout, image size, colours, backgrounds, margins, and so on. Likewise, readers wish to customize styling without being at the mercy of bad web designers. **Cascading Style Sheets (CSS)** is a web standard that gives both authors and readers control over styling. 

A web server will serve web browsers both HTML and CSS. User may supply her own stylesheet. Browsers will render the content according to the styles defined in one or more stylesheets. In addition, when these stylesheets don't define styles for some elements, browser will apply its own defaults. 

CSS is a stylesheet language. It's standardized by W3C.

## Discussion

### What are the benefits of using CSS?

Back in 2002, Wired and ESPN were among the first sites to redesign their websites. They saw better performance, faster design changes, and easier style sharing. 

One of the best practices of web design is to keep content and structure separate from presentation and styling. HTML provides the structure while CSS provides the styling. Before CSS, authors used **presentational HTML markup**, now deprecated by W3C. For example, if a `h2` tag had to be styled in a certain way, this extra markup would be included in every instance where the tag occurred. This made it difficult to maintain the code. 

The **cascading** aspect of CSS is important. Both web authors and readers have control over styling. The author may choose to show `h3` tags in italics but the reader may have a different preference. The reader can therefore customize the style. Elements for which no styles are defined, browser defaults apply.  

Another important concept is **inheritance**. An element inherits styles of its ancestor elements (parent, grandparent, etc.). The element itself can have an overriding style declaration. 


### Is CSS a programming language?

Some don't consider CSS a programming language. Others view CSS as a **declarative domain-specific programming language**. 

It's declarative because CSS specifies a bunch of constraints. It tells rendering engines what's required but not how it should happen. Unlike an imperative language such as JavaScript, CSS doesn't give step-by-step instructions on how rendering should be done. This implies that control flow is implicit in declarative languages. 

Unlike general purpose languages such as C or Python, CSS is domain-specific. It's been created for styling elements on a webpage. 

On the final point about being a programming language, the very definition of the phrase "programming language" can be narrow or wide. CSS has functions, variables, math, and more. It wouldn't be entirely wrong to consider it a programming language. 


### How do I specify a style in CSS?

We can style an element by specifying a *property* and assigning a *value* to that property. Property and value are separated by a colon. Taken together, the syntax `property: value;` is called a *declaration*. Multiple declarations can be specified for the same element and these are separated by semi-colon. For readability, each declaration can be on a separate line. Multiple declarations are grouped together for the same element using a pair of braces `{...}`. 

We also need to select a DOM element to which the CSS declarations are to be applied. This is done using the *CSS Selector*. There are many ways to specify the selectors including class name, identifier, tag name, attribute value, and more. The position of the element within the DOM structure can also be used. For example, `li.active a` selects anchor tags appearing within list items of class `active`. 

A CSS selector plus its set of declarations are jointly called a *ruleset* or simply a *rule*. 


### Which are the CSS properties and their permitted values?

CSS properties and values are too numerous to mention here. We share some of them to give you a sense of what's possible in CSS: 

    + `background`: example values include `green` (colour), and `no-repeat url("../../media/examples/lizard.png")` (image).
    + `border`: use `2px dotted` for width and style.
    + `color`: specify the foreground (text) colour with values such as `#00ff00`, `red`, `rgb(214, 122, 127)`, and `hsla(30, 100%, 50%, .3)` (with alpha value as fourth argument).
    + `float`: control the wrapping of an element around other elements with values such as `none`, `left`, `inline-start` and `table-row`.
    + `font-weight`: control font boldness with values such as `normal`, `bold`, `bolder`, `lighter`, `100`, and `400`.
    + `margin`: use `1em` margin on all sides or `2px 1em 0 auto` margin on top, right, bottom and left respectively.
    + `text-decoration`: an example value is `underline dotted red`, which specifies line, style and colour.All properties accept values `inherit`, `initial` or `unset` to revert to ancestor or global values. 

Some properties such as `margin` are shorthand forms. For better readability, longer forms may be used, such as `margin-top`, `margin-right`, `margin-bottom` and `margin-left`. 


### How are CSS styles delivered to clients for rendering a webpage?

One common way to do this is to save all CSS rules within a file of extension `.css`. A stylesheet is linked from HTML pages using the `<link>` tag. Browsers will request the stylesheets when they see these links. An alternative is to include CSS rules with HTML `<script>...</script>` tag. The third method (not preferred) is to inline the styles with each element using the `style` attribute. It's possible to combine all these approaches for a single webpage. Due to its cascading nature, CSS figures out the final style to apply for each element. 

CSS styles have global scope, meaning that a selector can target any element of the DOM. The early 2010s saw a trend towards Single Page Applications (SPAs). Frameworks such as Augular, React and Vue emerged. About mid-2010s, **CSS-in-JS** emerged as a new way to scope styles to specific page components. CSS rules were defined within JavaScript code of each component. 


### Which are the key features of CSS?

CSS has lots of features and we note a few of them:

    + **Animations**: Visual effects can be created for better user engagement, for example, on mouse hover. Using *CSS 3D Transforms*, a 360-degree view of a product can be displayed.
    + **Calculations**: Simple calculations to automatically size an element can be done with `calc()`.
    + **Custom Properties**: Defined at root or component level, browser will substitute all instances with its value. For example, it's useful for theming.
    + **Gradients**: Large images can be replaced with *CSS Gradients* that allow for smooth transitions across colours.
    + **Image Filters**: Background images, colours and gradients can be combined for creating visual effects. Images can be clipped or converted to grayscale.
    + **Layouts**: Beyond the use of tables, diverse layouts can be created with *CSS Grid* and *CSS Flexbox*.
    + **Media Queries**: These are useful for creating responsive designs. System-wide preference for dark mode can be fulfilled.

### Besides HTML, where else is CSS useful?

Even in the early days of CSS, it was recognized that stylesheets could apply to markup languages other than HTML. 

CSS has been used with HTML, XML and XHTML. While CSS is common in web browsers many other software also use CSS. PDF generators parse HTML/XML+CSS to generate styled PDF documents. E-books, such as the popular EPUB format, are styled using CSS. Style languages have adopted CSS for their custom requirements: Qt Style Sheets and JavaFX Style Sheets for UI widgets, MapCSS for maps. 

Of interest to developers, the popular jQuery library has the method `css()` to set and get any CSS property value of an element. For test automation, Selenium allows developers to select DOM elements using CSS selectors as an alternative to XPath selectors. 


### Could you share some developer resources for working with CSS?

Visit W3C site for a description of all CSS specifications or search for CSS standards and drafts. W3C also provides a free online CSS Validation Service to validate your stylesheets.

For a showcase on CSS capabilities, visit CSS Zen Garden. CSS-Tricks is a popular blog focused on CSS for developers. CSS Reference includes every CSS property and rendering of the same at different values. A similar site is DevDocs.

The CSS page at Mozilla's MDN Web Docs is a good place for beginners. The site has tutorials and shares a cookbook of common layout patterns. 

Nan Jeon has shared a handy cheatsheet on CSS selectors. Each example includes HTML structure and infographic. Make A Website Hub has published another useful CSS cheat sheet. 

## Milestones

1980

In the 1980s, stylesheets are created as part of Standard Generalized Markup Language (SGML). These are named Document Style Semantics and Specification Language (DSSL) and Formatting Output Specification Instance (FOSI). Though considered for the Web a decade later, they have a limitation: they can't combine styles from different sources. 

Dec  
1990

Tim Berners-Lee has a working web server and a browser on his NeXT computer at CERN. There's no CSS at this point but Berners-Lee recognizes that it's good to keep document structure (content) separate from its layout (styling). His browser has the means to select style sheets. He doesn't publish the details, leaving it to browsers to control styling. Indeed, when Pei-Yuan Wei creates the ViolaWWW browser in 1991, it comes with its own stylesheet language. 

Oct  
1994

Håkon Wium Lie releases a draft titled *Cascading HTML Style Sheets*. This gets discussed, along with alternative proposals, at the Mosaic and the Web Conference in Chicago in November. Lie's proposal has the advantage of being designed for the Web. Styles can be defined by the author, the reader, the browser or even based on device display capabilities. Lie's proposal could combine or "cascade" styles from different sources. 

Aug  
1996

Microsoft's Internet Explorer (IE) becomes the first commercial browser to support CSS. IE has good support for font, colour, text and background properties but poor support for the box model. When IE6 comes out in 2001, it has much better support for CSS and a browser market share of 80%. 

Dec  
1996

**CSS Level 1** or **CSS1** is released as a W3C Recommendation. CSS1 allows styling of fonts, colours, background, text, and lists. Box properties include width, height, margin, padding, and border. A revised version of CSS1 is published in April 2008. In September 2018, W3C officially supersedes this by more recent Recommendations. 

May  
1998

**CSS Level 2** or **CSS2** is released as a W3C Recommendation. It's now possible to position elements and style page layout using tables. To target media types and devices, `@media` rule is introduced. CSS2 expands the syntax for selectors. 

Oct  
1998

Each browser renders CSS1 differently due to non-conformance to the specifications. Todd Fahrner creates the "acid test", a CSS1-styled document that a browser must render exact to the pixel. This is based on the work done by Eric Meyer and others who developed a CSS test suite. In later years, more acid tests are defined. These are available at acidtests.org.

Jun  
1999

The first drafts for **CSS Level 3** or **CSS3** are published by W3C. In fact, work on CSS3 started just after the release of CSS2. Unlike, CSS1 and CSS2, CSS3 takes a modular approach. There's no single document. 

May  
2003

Across browsers, support for CSS is inconsistent. Web designers prefer to avoid CSS and use HTML tables instead. Web designer Dave Shea sets out to change this by showcasing good CSS designs. He launches the website *CSS Zen Garden* with simple HTML content that could be styled differently by changing only the CSS. He showcases five of his own examples. A little later, he allows public to submit their own CSS designs.  

May  
2011

CSS3 is a collection of separate documents. It becomes difficult to release these documents due to interdependencies. It's therefore proposed that CSS3 will be based only on CSS2.1. Each document will have its own levelling. When CSS2.1 becomes a Recommendation, stable modules of CSS3 will also become Recommendations on their own. This modularization doctrine is documented in the *CSS Snapshot 2007*, which is meant for implementors to know the current state of standardization. 

Jun  
2011

**CSS Level 2 Revision 1** or **CSS2.1** is released as a W3C Recommendation. CSS2.1 fixes some errors present in CSS2, removes poorly supported features and adds features already supported by browsers. It comes after more than a decade of edits, often changing status between Working Draft and Candidate Recommendation.  Subsequently, for CSS3, CSS Color Level 3, Selectors Level 3, and CSS Namespaces are published as Recommendations. 

Apr  
2020

CSS now has more than a hundred documents at different levels. It may no longer make sense to use the terms "CSS3" or "CSS4". CSS continues to evolve with more capabilities.