CSCE 120


CSS

Mr. Bert Bos, co-inventor of CSS

Source: youtube.com

Accorging to Mozilla Developer Network (MDN), Cascading Style Sheets (CSS) is a stylesheet language used to describe the presentation of a document written in HTML or XML (including XML dialects such as SVG, MathML or XHTML). CSS describes how elements should be rendered on screen, on paper, in speech, or on other media.

CSS is the technology responsible for creating beautiful, flexible and responsive websites. Developers and designers are using CSS to control the formatting, presentation, and overall look of a web page.

This class will cover the following

Introduction to CSS

  • Introduction to CSS
  • CSS Rules
  • Applying CSS to HTML
  • How it works
  • Selectors and Properties
  • Cascading and Inheritance
  • Using Someone else's CSS

Styling Text

  • Setting Fonts
  • Text Styling

The Box Model

  • Display, position z-index properties
  • Margins, padding, borders, and custom background colors
  • Drop shadows and filters

Layout with CSS

  • Place elements in the right place in relation to the viewport, and another elements
  • Display inline
  • Float and positioning
  • Introduction to flexbox
  • CSS Grid Layout

Introduction to CSS

CSS instucts the browser to apply presentaion artwork to the html elements. For example, apply gray background to all paragraphs or a subset of paragraphs

Selectors and Properties
CSS rule image
Element Selector
CSS Rule

Selectors point to the HTML elements in the page

Declaration block are surrounded by curly braces, may contains one or more declarations separated by semicolons (semicolons is optional for the last decleration)

A Declaration consists of a property name and a value, separated by a colon

In addition to the name selectors, CSS enables developers to select HTML elements based on element's id, class, attribute, and more.

CSS is introduced to HTML in three ways
  1. Inline style
  2. Internal style sheet
  3. External style sheet
Inline style

Applying CSS directly to an individual HTML element using style attribute

css-intro-inline.html

Internal style sheet

Applying CSS to an HTML page using Style element in the page head

css-intro-Internal.html

External style sheet

Using an external css file and applying css using link element in the page head

css-intro-external.html

How it works

The browser receives the HTML page (URL) from the server, loads and then parses HTML. At the parsing stage, if the CSS is already part of the document (inline css), it creates Document Object Model (DOM). If not, it makes a seperate request to the server to reveive the css file. Then, it loads the CSS and then parses. After that it creates DOM. Once DOM is ready, the browser renders the page (displays the content of the DOM).

DOM

The Document Object Model (DOM) is a programming interface for HTML and XML documents. DOM has an upside-down tree-like structure (leafs are at the bottom) which represents the page as nodes and objects. DOM can be modified with a scripting language such as JavaScript.

More Selectors

In addition to the element selector, which targets all elements with the specified element name, CSS provides many more selectors.
The Id Selector

Id selector matches an element based on the value of its id attribute


    <h1 id="main-title">The Main Titl of My page</h1>

    #main-title { 
        text-align: center;
        color: red;
    }

    [id=main-title] an be used instead of #main-title
The class Selector

class selector matches elements based on the contents of their class attribute.


    <p class="red-text">paragraph with red text</p>
    <p class="red-text yellow-background">paragraph with red text and yellow background</p>
    <p class="red-text italic-text">paragraph with red and italic text</p>

    .red-text {
    color: #f33;
    }

    .yellow-background {
    background-color: #ffa;
    }

    .italic-text {
    font-style:italic;
    }

    [class~=red-text] an be used instead of .red-text

The attribute Selector

attribute selector matches elements based on the contents of their class attribute.


    /* <a> elements with a title attribute */
    a[title] {
    color: purple;
    }

    /* <a> elements with an href matching "https://cse.unl.edu" */
    a[href="https://cse.unl.edu"] {
    color: red;
    }

    /* <a> elements with an href containing "students" */
    a[href*="students"] {
    font-size: 2em;
    }

    /* <a> elements with an href ending ".edu" */
    a[href$=".edu"] {
    font-style: italic;
    }

    /* <p> elements whose class attribute starts with the word "logo" */
    a[class^="logo"] {
    padding: 8px;
    }

The universal Selector (*)

universal selector (*) matches elements of any type


    /* Selects all elements */
    * {
       color: green;
    }

Combinations of of more than one Section

The adjacent sibling combinator Selector (+)

adjacent sibling combinator (+) separates two selectors and matches the second element only if it immediately follows the first element, and both are children of the same parent element.


    <div>
        <p>
            Paragraph before div element
        </p>
        <div>
            Div element
        </div>
        <p>
            Paragraph immediately after element
        </p>
        <p>
            Paragraph after another Paragraph element
        </p>
    </div>

    /* Paragraphs that come immediately after any div */
    div + p {
        font-style: bold;
    }

The descendant Selectors ( )

descendant selectors ( ) matche the elements only if they have an ancestor element matching the first selector


    <div>
    <p>Paragraph before div element</p>
    <div>Div element</div>
    <p>Paragraph immediately after element</p>
    <p>Paragraph after another Paragraph element</p>
    </div>

    /* Paragraph that are descendants of a div */
    div p {
    font-style: bold;
    }
    /* Paragraph that are descendants of the "students" list. students is a class */
    div.students p {
    padding: 2em;
    }
The child Selectors ( > )

child selectors ( > ) matches the second selector that are the children of elements matched by the first.


    <div class="students">
    <p>Paragraph before div element</p>
    <span>
       <p>Paragraph not a child of div.students</p>
    </span>
    <p>Paragraph immediately after element</p>
    <p>Paragraph after another Paragraph element</p>
    </div>

    /* List items that are descendants of the "students" list. students is a class */
    div.students p {
    padding: 2em;
    }

Pseudo-classes and Pseudo-elements

Pseudo-classes allow the selection based on the state an element.

Pseudo-elements targets a specific part of an HTML element, not the element itself.


    /* Any <a> (link) over which the user's pointer is hovering */
    a:hover {
    color: black;
    }
    /* The first line of every <p> element. */
    p::first-line {
    text-transform: uppercase;
    }

Pseudo-classes
--------------
:active
:checked
:default
:defined
:disabled
:empty
:enabled
:first
:first-child
:first-of-type
:focus
:focus-within
:host
:host()
:hover
:indeterminate
:in-range
:invalid
:lang()
:last-child
:last-of-type
:left
:link
:not()
:nth-child()
:nth-last-child()
:nth-last-of-type()
:nth-of-type()
:only-child
:only-of-type
:optional
:out-of-range
:read-only
:read-write
:required
:right
:root
:scope
:target
:valid
:visited

Pseudo-Elements
--------------
::after (:after)
::before (:before)
::cue (:cue)
::first-letter (:first-letter)
::first-line (:first-line)
::selection
::slotted()

Cascading Order

The notion of cascading in CSS is important to understand. Basically it refers to the hierarchical order in which different style types interact when more than one rule applies to a single element and therefore when conflicts arise. For example: When there is more than one style specified to an HTML element, one setting the background to green and the other setting to red, which style will will be applied? The short answer: The rule with higher precedence (weight) will take affect.

The cascading occurs in this order

  1. Browser Defaults Styles
  2. User Styles
  3. External Styles
  4. Internal Styles
  5. Inline Styles

Inline, Internal External sytles are author styles. Author styles have higher prescedence than User Styles which have higher prescedence than Browser Defaults Styles.

The higher the number, the higher the precedence. Inline Styles has higher prescedence (5) then Internal Styles (4) and so on.

Basicaly, if two styles come into conflict, the one with higher precendence will be applied and override the othe ones. This is often the last one used.

Basically the closer the the css to an element the highert its presidence. In other word, the css that applies the last, wins the race. When all other conditions are the same, the inline-css will win and override the internal, external and browser styles

The inline style has the highest priority, and will override the internal, external and browser defaults styles

It is important to recognize that this happens only when two contradicting styles are applied to the same HTML element

css-precedence.html

Selector Type Precedence

The selector type precedence occurs in this order

  1. Element
  2. Class
  3. Id

When there is an element with a class and Id selector, and they contained conflicting styles, the Id style takes precedence and override the class style

css-selector-type-precedence.html

More than one selector rule may apply to a given element. When this occurs, the browser follows the Specificity rule to decide which rules to apply

CSS Inheritance

The idea of inheritance is simple: The property values (styles) applied to an element will be inherited by the elements children. Reverse is also true: A child element will take on the property values of the parent element. What if you want the child element to take on some rules of the parent but not others? Developer will simply override the rules that need not to be inherited.

css-inheritance.html

The !important Rule

Utilize the !important rule only to make sure that the most crucial styles are always applied. Use this rule only when necessery. Again, It is important to know that the !important is only useful when two contradicting styles are applied to the same HTML element.

css-inheritance.html

Often when using a framework or someone else's css libraries, you might want to change the basic visual aspect to fit your needs. Instead of making changes to the sourse file, it's best to override some aspects. This could be done using !important

Styling Text

Styling Text using CSS, is generally involves two groups

  • Font styles
  • Text layout styles

Font styles

These are the properties that affect font which is applied to the text. Properties are: color, font name(s), font family, font size, font style, font weight, text transform, and text decoration.

color


    p, .red-text {
    color: red;
    }

font-family


    p .screen-read {
    font-family: arial;
    }

Some fonts are supported by certain computer systems only. The fonts that are supported by all systems are known as web safe fonts.

Web safe fonts
Name Type
Arial sans-serif
Courier New monospace
Georgia serif
Times New Roman serif
Trebuchet MS sans-serif
Verdana sans-serif

CSS divides font family names into generic and non-generic families. Generic names for fonts are serif, sans-serif, monospace, cursive and fantasy

Non-generic names for fonts are times, courier, arial, more...

When writting font rules, start with the font that you hope to use, and always end with a generic family for a fall back. There is no garantee that the font s you want to use will be supported by the browser, one should always supply font stacks. Separate each name with a comma and If a font name contains white-space, it must be quoted.


    <p class="cool-font"> A paragraph with several font family </p>
    .cool-font {
    font-family: Helvetica, "Trebuchet MS", Arial, Verdana, sans-serif;
    }
font-size

By default, the font-size of an element is inherited from that element's parent element, however developers have the ability to override this behavior. font-size can be set using one of these units: px, em, rem

px which is an absolute unit, represents the number of pixels high for the text. This value does not change when screen size changes

em is a relative unit. 1em is equal to the font size set on the parent element. When the size of the parent element changes, so does the font size of the current element.

eem is a relative unit. 1rem is equal to the font size set on the root element of the document which is html.

Not all browsers support relative units.

css-fonts.html

Font Styles effecting Text

font-style set the text to one of these fonts: normal, italic, oblique

font-weight set the text's boldnes: normal, bold, bolder, lighter, numeric values: 100–900

text-transform sets text transformation: none, uppercase, lowercase, capitalize, full-width

text-decoration sets text decorations: none, underline, overline, line-through

css-fonts.html

Text Shadows

CSS has the functionality to add shadow to text.


    <p class="with-shadow"> A paragraph with Text Shadows </p>

    text-shadow: h-shadow v-shadow blur-radius color|none|initial|inherit;

    .with-shadow {
    text-shadow: 4px 4px 6px green;
    }

    Multiple shadows
    ----------------
    text-shadow: -1px -1px 1px #ddeeff,
    0px 4px 1px rgba(0,0,0,0.5),
    4px 4px 5px rgba(0,0,0,0.7),
    0px 0px 7px rgba(0,0,0,0.4);

h-shadow and v-shadow are required

css-fonts.html

Text Styling

CSS provides several prperties for text layout and styling. Below are some of the most commonly used properties. For a complete list, check out online

text-align property is used to set alignment of the text within its container. This property works the same way as any regular word processor. Possible values are left, right, center, justify

line-height property sets the height of a line of text

letter-spacing property sets the spacing between letters in the text

word-spacing property sets the spacing between words in the text

word-wrap tells the browser to break lines within words

The Box Model

Every HTML elemenet will produce a rectangular box. Each box includes content, padding, border and margins. Understanding how to size and arragnge the boxes is a critical step toward understanding web desing.

CSS Box Types

CSS provides many types through display propery. The basic ones are block, inline, inline-block

In the Layout section, we will talk about a few more such as flex, table-row and grid

block which is the default display property of most elements, set the element to display as a block. Blocks stack on top of each other

inline is the opposite of a block box. its content breaks with the flow of the text

inline-block flows with surrounding text and other inline elements without creating line breaks before and after. This is something in between block and inline

css-display.html (display and visibility)

Box Properties

standard box model
Standard box model

width, height properties set the width and height of the content box as seen in the image above

padding property sets the space between content and the border of the element

border property sets the style of the border. Adds spave between padding and margin

margin property set the space around the element.

css-box-model-basic.html

Better Box with box-sizing

box-sizing alters how the total width and heigh of a box is calculayed

border-box model
The box model with

css-box-model-better.html (with box-sizing)

CSS Layout

CSS provides seveal techniques for creating desired layout. In this cahpter, we will start with reviwing the basic normal flow of elements in the page. Element positioning, realtive to the parent elemet as well as the document, will give us the opportunity to move elements to a different location in the page. Floting content, which was very popular in the past, will enable us to wrap block level elements to move left or right for creating magazine like content. Most importantly, we will cover table layout, flex layout and grid layout.

The browser will stack the block level elements on top of each other, by defaoutl, this is also know ans normal flow. Simply, there is no css to effect the positioning of any element. The position of an element, by default, is static

Normal flow

Element Positioning

Using positioning, one can take HTML elements out of normal document flow, and make the display differently. Elements can be can be positioned in different location relative to the parent element, the document and the window. Position may be altered for each screen size as well.


    selector {
        position:value;
    }

static is the default position. In other word, no position is applied. The element is positioned according to the normal flow of the document

relative moves an element from it's default position in some direction

absolute and fixed removes the element from flow of a documnet. absolute moves an element to a specific position relative to the body of the document. fixed moves an element to a specific position relative to the windows (not the document). Scrolling will not effect the visibility.

CSS position

Display Property

In the CSS Box Types section we have already covered the basic display properties such as block, inline, inline-block, and none. Before we move on to more advanced display properties, we will demonstrate float which is not a display property, however float was being used for layout as well.

float is used for wrapping images inside blocks of text. It can also be used for layout: sections of the page may be floated left or rght. Once an element is floated, it effects all the block level elements that follow it in normal flow. In order to make sure the following elements follow the normal flow, developers often clear the float.

.clearBoth {
        clear:both;
    }

Float Example

Advanced display properties: flex, and grid

Before we start with modern display properties, it is worthwhile to mention that display: table was quite popular for a long time. Table layout is designed for laying out 2D data in a tabular format. While it's still widely used, it is considered a legacy layout method.

Flexbox or flex layout

Flex or Flexbox layout was introduced for laying out more complex applications. In its core, it's similar to block layout with many flexible options. Often, the container is know as the flexbox and is one-dimentional. Items in the flexbox, may be laying in rows or columns, and flex to fill available space and shrink to fit into smaller spaces.

CSS community used float, positionong and table to generate desired layouts for years. These worked for the majority of the developer community however these options were not designed for an intuitive layout. Flexbox enhances the notion of layout in several ways - below list is a subset of what flex introduces:

  • Specifying the direction that content may be laid out
  • Vertically centering a block of content
  • Ability to layout as a single line or multiple lines
  • Making all the children of a container take up an equal amount of the available width/height, regardless of how much width/height is available
  • Making all columns in a multiple column layout adopt the same height even if they contain a different amount of content
  • Ability to dynamically collapse or uncollapse

Flex Example

CSS Grid Layout

Before flex (or flexbox) was available, developers were using tables, display:inline|inline-block|block|table, float and many other positioning hacks to achieve desired layouts. Flex solved a lot of issus related layout and brought easy notion to manage layout using CSS. However, it turned out that flex had it's own short comings.
Flex provides a layout method for one-dimensional layout. One-dimensional means that you may lay out your content in a either row, or column, but not both, unless you use css rules beyond the scope of flex.

The CSS community searched for something better and came up with CSS-Grid. CSS-Grid is for two-dimensional layouts. Rows and columns both can be utilized. When there is only one row or one column container, it will behave as flexbox substitute.
There has been two level of specifications since the inception of CSS-Grid. CSS Grid Layout Module Level 1 is W3C Candidate Recommendation while CSS Grid Layout Module Level 2 is W3C Working Draft
According to Can I Use, CSS-Grid has over 90% of the support amoung the major browsers already.

Grid Terminology
Think of Grid as Table

Grid Lines are the lines that make up the grid. These can be horizontal or vertical. We can refer to them by number, or by name.
Red line on this table is column line 2

Grid Track is the space between two Grid Lines, either horizontal or vertical
Grid Track on this table is between row lines 6 and 7.

Grid Cell is the space between 4 Grid Lines. It is the smallest unit on the grid that is available to place an item
Grid Cell on this table is between row lines 4 and 5 and column lines 3 and 4.

Grid Area is any area on the Grid bound by four grid lines. It may contain a number of Grid Cells.
Grid Area on this table is between row lines 1 and 5 and column lines 5 and 7.

Now that we are familiar with the basc teminology, let's define the grid layout and what it can do. A grid is basically a pattern of regularly spaced horizontal and vertical lines forming squares on a surface. CSS grid enables us with pattern against which we can line up our html elements. A grid will typically have columns and rows.

To turn an HTML element into a grid, use the grid value of the display property.
.container {
                display: grid;
            }

After turning our container into a grid, we can add columns and rows. We can specify the size of each cell to be different or we can choose to have a flexible grid that has all cells the same size. pixels (px) or percentage can be used when the size of cell are defined. Grid introduces a new unit, fr, which is for flexible size grid rows and columns

.container { display: grid; grid-template-columns: 1fr 1fr 1fr; /* or 100px 100px 100px; */}
CSS Grid Examples

What About Mobile Devices?

I want to use my phone

Responsive Design

WhatIs.com describes Responsive design as follows: Responsive design is an approach to web page creation that makes use of flexible layouts, flexible images and cascading style sheet media queries. The goal of responsive design is to build web pages that detect the visitor's screen size and orientation and change the layout accordingly.

The above description introduces new termoinology such as media queries and also the last sentence mentiones "visitor's screen size and orientation". In other word, this sentence suggest that CSS should be able to detect "visitor's screen size and orientation" and supply seperate CSS rules. Such a solution is made possible by media queries

Introduction to Media Queries

Media Queries enable developers to apply a subset of CSS rules to the HTML document. It uses the @media to specify a certain condition such as screen resolution (i.e phone screen or tablet screen or computer screen). These conditions are made of media type in conjunction with size information. Often, this is known as breakpoints which are the point a which the page content will respond to provide the user with the best possible layout to consume the information.

@media condition  { /* Apply this rule, only of the condition is true */}

Below is a list of commonly used media types

  • all (suitable for all devices)
  • braille
  • embossed
  • handheld
  • print
  • projection
  • screen
  • speech
  • tty
  • TV
    /* Extra small devices (portrait phones, less than 576px)
    No media query for Mobile First Design (default in Bootstrap 4)
    }
    /* Small devices (landscape phones, 576px and up) */
    @media only screen and (min-width: 576px)  {
    /* Code (rules) in here only applies to screens in the rendering surface width of 576px */
    }
    /* Medium devices (tablets, 768px and up) */
    @media only screen and (min-width: 768px)  {
    /* Code (rules) in here only applies to screens in the rendering surface width of 576px */
    }
    /* Large devices (desktops, 992px and up) */
    @media only screen and (min-width: 992px)  {
    /* Code (rules) in here only applies to screens in the rendering surface width of 576px */
    }
    /* Extra large devices (large desktops, 1200px and up) */
    @media only screen and (min-width: 1200px)  {
    /* Code (rules) in here only applies to screens in the rendering surface width of 576px */
    }

Here, we used min-width. We can also use max-width as well.

Mobile First

min-width is used for taking the smallest device into consideration first. CSS for mobile devices will be rendered first, then CSS for larger ones will override. This makes sense because smaller devices often have limitted processing power. When there is less CSS, the page will load faster. This is used as a performance trick and is a best practice

However, often developers ommit following the Mobile First approach. The flip side is using max-width. This approach largest device into consideration first. CSS for mobile devices will override some of the CSS for for proper doisplay in the smaller devices In this case, smaller devices will apply the CSS written for the larger devices, then apply the CSS written for the smaller devices. This will require more processing and delay in document load. This practice is widely used, but not a good method for performance considering more users access web using mobile devices than PCs.

Media Queries

Putting all together

CSS Frameworks

Over the years, the developer community learned, documented and come up with easy ways to manage CSS. Developers created CSS independently and maintained their own CSS code. This continued for years. It turned out that most developers wanted to create similar layouts, also some developers found CSS combersome because CSS was not a programming language like C, C#, Java. CSS frameworks came to rescue to allow for easier, more standards-compliant web design.

The two widely used frameworks are Bootstrap and Foundation. More can be found online

CSS is neither a programming language, nor a markup language — it is a style sheet language

CSS is the language for describing the presentation of a document written in a markup language, like HTML

CSS describes how elements should be rendered.

CSS rule sets are made of selectors and decleration(s) which consists of properties and property values

CSS rule sets are interpreted by web browsers

CSS seperates style from content

  • Maintainable
  • Reuseable

CSS provides many properties

  • Evolving toward mobile and animations

CSS can be used

  • By writting fron scratch
  • By using frameworks (external libraries)