infuerno.github.io

Treehouse DD CSS Foundations

Mozilla CSS reference: https://developer.mozilla.org/en-US/docs/Web/CSS/Reference

Stylesheet types

Selectors

Universal selector

The universal selector * is very powerful and can be used to select all elements. Useful for removing all margins and paddings from user-agent stylesheets.

Type selectors

e.g. body, h1, table

Descendant selectors

Only select elements which are decendants of other elements.

h1 span { color: blue;}  
.base p { padding: 5px;}

Class and ID selectors

Both a class and an ID can be applied to an element. IDs carry more specificity than classes, so styles defined in IDs will carry more weight than styles defined in classes.

Combinators

Selectors can be combined using a combinator.

Direct child

> selects elements which are only direct children of the element on the left

h1 > a { color: blue;}  

Adjacent sibling

+ selects elements which are immediately adjacent to the element on the left

h2 + p { font-size: 1.2em; } 

General sibling

~ selects all sibling elements, not only those immediately adjacent, to the element on the left. Note it will select all elements which follow as long as they are siblings (i.e. on the same level) even if they are separated by other elements, but no elements which are before.

h2 ~ p { font-size: 1.2em; } 

Attribute selectors

Select all elements which have a certain attribute.

Attribute selectors have the same specificity as classes and pseudo classes.

Pseudo classes

Structural pseudo classes

Additional pseudo classes

UI element states pseudo classes

Substring matching attribute selectors

Begins with ^=

Ends with $=

Contains

Pseudo-elements

The difference between psuedo-elements and psuedo classes is that psuedo classes target actual elements, whereas psuedo-elements target virtual elements which don’t always exist as elements.
The two syntax variations :first-letter and ::first-letter will both work, but the double colon is more common to distinguish that this is targeting a psuedo element.

Two further pseudo-elements allow inserting generated content.

Both require a content property which can specify the content to be inserted in a number of different ways: the actual content as a string; a url to an image; a reference to the content of an attribute on that element; or an empty string with extra css properties to e.g. draw a circle.

.phone::before { content: "\2706"; /* common phone icon unicode */ }
.phone::before { content: url("img/phone.jpg"); }
.dload::before { content: attr(href); }
.dload::before { content: ""; height: 50px; width: 50px; display: inline-block; }

Note the generated contented is inserted into the actual element, rather than alongside.

Values and units

Absolute length units

Reference: http://www.w3.org/TR/css3-values/#absolute-lengths

These are only useful when the dimensions of the output are known e.g. cm when printing, px when viewing on a screen.

Unit Description Notes
cm Centimeters Not commonly intended for web design, highly dependent on output and varies greatly between different resolutions
mm Millimeters
in Inches
pc Picas Commonly used in print, not intended for web or screen design (1pc = 12pt = 1/6 inch)
pt Points Commonly used in print, not intended for web or screen design (1pt = 1/72 inch)
px Pixels 1px used to be 1/98 inch, but now pixel densities are changing, this changes too

An alternative method for pixels instead of relating physical units to physical measurements on a screen, the concept of a reference pixel - an optically consistent reference unit.

Except for pixel units, all other absolute units tend to be avoided, except in cases when desigining for printing.

Relative length units

Unit Description Notes
ex The height of the current fonts lower case letter ‘x’ Different fonts even with the same font size may have differently sized 'x’s.
em Relative to the font size of the parent element The default font size is 16px, em is useful since it will resize according to the default font size chosen by the user. Nested elements get tricky.
rem Root em, always relative to the root element

Viewport relative units

Size is based on the size of the viewport and is 1% of this size. Currently have less browser support. Check out http://caniuse.com/viewport-units

Unit Description Notes
vw viewport width Measured in 1% units of the width of the view port e.g. 15vw is 15% of the width
vh viewport height 1% units of the height of the view port
vmin viewport width or height, whichever is the smaller 1% units of the width or height
vmax viewport width or height, whichever is the larger 1% units of the width or height

Numeric and text data values

Color values

Text, Fonts and Lists

Fonts

Reference: http://www.w3.org/Style/Examples/007/fonts.en.html

The generic fonts are serif, sans-serif, monospace, cursive and fantasy. CSS properties for fonts are font-family, font-weight, font-variant (small-caps), font-style (italic, oblique). These can all be expressed in one line:

p {
    font: [font-style] [font-variant] [font-weight] font-size font-family;
}

White space

The white-space property is used to alter the display of whitespace.

Shadows

p {
    text-shadow: x-offset y-offset shadow-size colour;
}

Multiple shadows can be applied by seperating each shadow definition by a comma. The first one defined will be “on top”.

Overflow

The text-overflow will determine the style if text is spilling outside of a container (e.g. due to white-space: nowrap style). Possible values are hidden and ellipses.

The word-wrap property can be set to break-word to ensure a long string wraps to be contained within one container.

List bullet styles

Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-type

As with fonts, the list-style property can be used to define everything in one. Parts are optional and the order does not matter.

Box model

Block level elements take up the full width available from the parent element, plus a new line before and after.

border-width, border-style and border-color properties can take up to four parameters to uniquely style each of the four sides of the element.

Negative margins

Inline block

The value inline-block for the display property generates a box which is a block element flowed with surrounding content. Note negative top and bottom margins cannot be applied to inline-block elements

Width

The width property specifies the width of the content. To get the complete width used up by an element, the width, padding, border and margins need to be added together.

The box-sizing property allows you to alter this behaviour if you give it the value border-box (-moz-box-sizing in mozilla)

Height

The height property will work depending on the height of the parent container. min-height and max-height can be used to control the height independently of the content. If the content is too big, it will flow outside of the container. This can be controlled with the overflow property to scroll the contents if desired.

Floats

Clearing floated elements can be done in several ways. The most semantic is achieved using the following piece of css:

.group:before,
.group:after {
  display: table;
  content: "";
}
.group:after {
  clear: both;
}

Positioning

Backgrounds

background: [background-color] [background-image] [background-repeat] [background-attachment] [background-position]

Border radius

The border radius will be applied if there is either a border or a background. Negative units cannot be used. Horizontal and vertical radius can be given seperately. When using the border-radius shorthand to define all corners together, the horizontal and vertical radii can be expressed using a slash.

Box shadows

box-shadow: [inset] [horizontal-offset] [vertical-offset] [blur-radius] [spread-radius] [colour]

Multiple values can be specified using a comma to seperate them, the first is rendered on top.

Border images

border-image: [source] [slice] / [width] [repeat] [outset];

Note always define fall back borders before the border-image definition.

Reference: http://border-image.com, http://css-tricks.com/understanding-border-image/

Multiple background images

Multiple sets of values can be set for the background property to layer mulitple backgrounds or background images on top of each other.

Typography

Legibility

Legible typefaces usually have many common features:

Legibility can be lost if:

Can the font do the job?

Readability

If we give users a reason to stop reading, they will.

Line length is most comfortable at 45 to 75 characters to one line (this includes spaces and punctuation).

Line height should also be generous - no less that 150%. Browsers default line height is usually 1em which is too small to be readable. Many factors can affect line height - typeface design, font size, weight and case. Also the longer the line length, the greater the line height which generally is needed.

Text has a natural rhythum which is created when we read. Designers can create the typographic rhythm to break up the monotony of a page. Readability heavily depends on it. Adding images and different heading colours helps create rhythm.

Typographic colour of a page refers to the density or tone of text and will affect readability.

Chunking involves grouping related elements together e.g. a heading and a paragraph. Text needs white space to breathe and to emphasis the content.

Visual hierarchy is important in order to enable skimming through the page. A good example is http://simplebits.com.

Three common approaches to the page:

  1. The traditional approach - uses a lot of centre and justification with text usually framed, in one or two columns. The text is meant to be contemplated, so is often decorated with text.
  2. The modernist approach - clear cut margins and edges, many columns, aligned to a grid.
  3. Post modernist - often breaks the rules, challenges the reader to make sense.

Responsive text

Typographic scales are often used to ensure consistency in combining different font sizes. A common scale is 6 7 8 9 10 11 12 14 16 18 21 24 36 48 72.

Convert font sizes in pixels to ems remembering that 16px = 1em. 1rem can be used to reset the font to 16px for nested elements.

Set widths of container divs in percentages instead of pixels to maintain margins when the viewport width changes. Media queries can be used to alter the defaults when the width is very small or very large.

@media screen and (max-width: 599px) {
    body { font-size: 1em; }
    .wrap { width: 85%; }
}

Line breaks in titles with changing viewport widths can be resolved by:

  1. Making the font-size smaller and / or using additional media queries to introduce ever changing font-sizes.
  2. Using the new vw font-size measurement (1/100th the width of the viewport) - not well supported currently and bug in chrome
  3. Use fittext jquery plugin from http://fittextjs.com. Link to jquery and to the fittext library, then add some javascript to select the element (using jquery syntax) and calling the method fitText() on it.

Vertical rhythm

This is the balance of spacing and arrangement of text as the user reads down the page. If each line of text fits consitently on evenly spaced baselines, then the page has a consistent vertical rhythm.

A useful tool to achieve this is availble from http://baseline.it. Just include a link to the stylesheet of the base line height in order to draw these lines behind the text on the page.

Web fonts

Populate font services include:

The @font-face css directive allows you to link to downloaded fonts using the font-family and src attributes.

Common font formats

Font stack

If web fonts are missing certain glyphs, the font stack becomes especially important in filling in any gaps. This mechanism can also be exploited by only specifying a small subset of glyphs in the referenced font-face e.g. ampersand to be used in the web page.

Icon fonts

Icon fonts can significantly speed up performance for icons and will scale to any size without losing quality.

These are added in exactly the same way as fonts, using the appropriate unicode. The -webkit-font-smoothing property may be useful with the value antialiased to get anti aliasing.

Ligatures

Open type font features can now be better utilised in css. Ligatures are used to improve the appearance of text when letters are too close together, connecting certain letters when they are next to each other.

-webkit-font-feature-settings: "liga", "dlig"; 

liga denotes common ligatures, dlig denotes discretionary ligatures.

Further enhancements

http://www.impressivewebs.com/html-entity-reference-common/ has a list of common entities http://dev.w3.org/html5/html-author/charref for a complete list

CSS Gradients

Reference: http://www.colorzilla.com/gradient-editor/

There are two types of gradients, linear gradients and radial gradients.

Linear gradients - prefixed syntax

A linear gradient is created when two or more colours are defined along the gradient line. By default the gradient line is from top to bottom. This can be changed, by including the horizontal and or vertical starting position either using position keywords or in degrees. Degrees start on the left and go anti-clockwise.

.box1 {
    background: -webkit-linear-gradient(bottom right, blue 100px, green);
}
.box2 {
    background: -webkit-linear-gradient(45deg, blue 50%, green);
}

Colour stops can be used to create more complex gradient effects, these require a colour component and optional position component. Positional components can be specified in percentages or pixels and specify where the colour stop should be shown at 100%.

Linear gradients - unprefixed syntax

.box1 {
    background: -webkit-linear-gradient(270deg, blue 100px, green);
    background: -moz-linear-gradient(270deg, blue 100px, green);
    background: -p-linear-gradient(270deg, blue 100px, green);
    background: linear-gradient(180deg, blue 100px, green);
}

Radial gradients - prefixed syntax

Radial gradients start at the centre and radiate out based on the parameters specified.

By default the shape is an ellipse and of the same proportions of the containing div. This can be changed to circular by adding the circle keyword (therefore not necessarily following the containing div’s proportions).

The centre of the gradient can be specified using two further parameters. If only one value is defined, the other value defaults to the centre. As with background images, the first parameter is from the left and the second from the top.

Further keywords can be defined to alter the gradient pattern.

As with linear gradients, further colour stops can be added with optional position components. The position component can be specified in percentages, pixels or em units and is measured from the centre of the radial gradient.

<position>, <shape> <size> followed by the colour stops

Radial gradients - unprefixed syntax

<shape> <size> at <position> followed by the colour stops

Transparent gradients

The transparent keyword can be used instead of a colour. This is actually just rgba(0,0,0,0). Better results may be achieved using an rgba colour of white with full transparency i.e. rgba(255,255,255,0).

If using a gradent for the background of the whole page, specify a height of 100% for the html element.

Repeating gradients

By using pixels in the colour stops this gives a repeating gradient pattern. repeating-linear-gradient and repeating-radial-gradient are the unprefixed versions.

The pattern repeats based on the difference between the first and last colour stop values.

Repeating gradients with smoother colour gradients can be created by making the last colour the same as the first.

Flexbox and Multi-column layout

New positioning system, consisting of a flex container and flex items. Flexbox defines how the flex items are laid out inside the flex container. The flex container can have multiple flex lines. By default these go left to right and top to bottom.

Axis : Flexbox has the concept of the main axis (default is left to right) and the cross axis (default is top to bottom).

Flex direction

.nav {
    display: -webkit-flex;                      // specify to use the flex layout mode
    -webkit-flex-direction: column-reverse;     // arrange items in a column (default is row)
    -webkit-justify-content: space-between;     // evenly distribute items
    -webkit-justify-content: flex-end;          // push items to the 'end'
    -webkit-justify-content: center;            // centre the items
}

Changing the margins around flex items, especially using auto, changes how the items are distributed in the container.

Wrapping

By default the items do not wrap, but spill out of the container. This behaviour can be changed with the property -webkit-flex-wrap and the attribute wrap.

Growing

To control how the items grow relative to the container and each other use the -webkit-flex-grow property. A value of 1 will ensure the free space is evenly distributed. The -webkit-flex property can also be used to specify ratio of space each item should take up. The -webkit-order property can be used to change the order, e.g. set it to -1 to move a particular item to the front of the other items. -webkit-align-self can take values such as center, flex-end to align individual items in a container (default is stretch).

Media queries can be used to ensure items do not become too small as the browser viewport is decreased, or alternatively to change the flow direction from row to column.

To use with browsers which don’t yet support flex box, the modernizr javascript can be used to provide a fall back solution.

Multi-column layout

-webkit-column-count : splits content into a specified number of columns

-webkit-column-gap : used to specify the width of the gap between columns

-webkit-column-rule : used to specify any rule to be drawn between columns. As with a border, there are three attributes which can be specified: width, style, colour.

-webkit-column-width : used to specify a max width for the columns and useful in responsive design.

-webkit-columns : used to combine the width and the count e.g. -webkit-columns: 250px 3;

Images can be rendered as well as text. Useful markup to have the image display and resize nicely:

img {
    display: block;
    width: 100%;
    margin: 1.5em 0;
}

-webkit-column-span : an attribute of all will allow an element to span all columns