Dano Manion

CSS Notes

My personal notes on CSS. 😊

Interweb References

  1. Mozilla.org Dev Network
  2. atozcss.com

Code Examples

  1. CSS-Only Menu

Anatomy of a Rule Set

  • Selector (targeting an): element .class #id
  • Property: border:
  • Value: solid gold 1px

      /* Gives you */
      Selector { Property: Value }
    
  1. List of Selectors
  2. List of Properties

3 Types of stylesheets

The closer the code is to the rule set, the more weight it carries in the cascade.

  • Inline style="property: value;"
  • Embedded <head><style> selector { property: value } </style></head>
  • External <link rel="stylesheet" href="style.css">

The Box Model

  • Every element on a webpage is a box.
  • The box model determines how wide and tall elements are on a page.
  • Each box is made up of:
    1. Content
    2. Padding
    3. Border
    4. Margin
  • Padding & Margin are added clockwise: Top, Right, Bottom, Left.
    • Example: padding: 10px (top) 10px (right) 10px (bottom) 10px (left);
  • Margin allows negative values, Padding does not!

The Key characteristics of a box can be defined as …

element { 
  width: 400px; 
  height: 200px; 
  margin: 20px; 
  padding: 20px; 
  border: 
  10 px solid gold;
}
  • Computed width: is calculated from the sum of it’s width, horizontal padding + horizontal border. Margin is not added.

    width = 400 + 5 + 20 + 20 + 5 (450px)

  • Computed height: is calculated form the sum of it’s height and vertical padding + border. Margin is not added.

    height: 200 + 5 + 20 + 20 + 5 (250px)

This can all change when using the ‘box-sizing’ model.

  1. Best Video I’ve ever seen describing this idea

Box-sizing

Starting with IE8💀 and up. We can now define the width of an element without padding adding it’s own width to the element. YAY! Padding and border no longer add extra pixels outside the width.

box-sizing: border-box;

  1. Example of box-sizing
  2. Border Width Property

Display properties

  • Block - take up the entire width of the view-port, or of containing element
    • Common examples: <h1>...<h6>, <p>, <blockqoute>, <li>, <div>, <section>, <nav>, <article>, <aside>, <header>, <footer>
  • Inline
    • Common examples: <em>, <strong>, <a>, <span>
    • inline-block: <img>
      • Note: img is actually known as a “replaced element” in that it has no content per se, and the element is essentially replaced by binary data.
      • Also, the gap underneith the image is actually caused from the image being on the base-line as it is NOT actually a bug. Because of this, developers will often change the display property value of img to display: block;.
  • Table
  • Table-Cell
  • Flex
    • Turns the first level children of any container into flexible items that share the available space.

Flexbox

  • IE10+ only! :(
  • The flexible box model
  • A simpler way to create flexible CSS layouts (as opposed to CSS floats and inline-block techniques)
  • Created for dynamic, flexible content

      // Add this to every project. 
      html, *, *:before, *:after { 
          box-sizing: border-box;
      }
    

Position

Specifies the type of positioning used for an element.

  • static (default) - nothing special, elements are positioned according to the normal flow of the page.
  • relative - is positioned relative it its normal position.
  • fixed - positioned relative to the viewport of the page
  • absolute - positioned relative to the nearest positioned ancestor.
  • sticky (Only: FF & Safari) - Keeps elements positioned as ‘fixed’ or ‘relative’ depending on how it appears in the viewport. As a result the element is ‘stuck’ when necessary while scrolling.

CSS Position API


Box Shadow

Attaches one or more shadows to an element.

  • box-shadow: x y blur color;
  • box-shadow: 0 8px 15px rgba(0, 0, 0, 0.3)

CSS Box Shadow API


Classes and IDs (Attributes)

  • Classes are a way to classify (tag) and element to specify how you would like something to look or behave.
  • IDs are the same way, however, they can only be used once and have more weight.

Pseudo Classes

Is designed to define a special state of an element. Alter the display or behaviour of ALL the contents inside an element box.

  • :active - Selects the active link.
    • When clicked on.
  • :focus - Selects the <input> element that has focus.
    • this could negatively impact usability in that it removing focus from elements could make it hard for users to see where their ‘tabs’ are. This is common in CSS Resets.
  • :hover - Selects links on mouse over
  • :link - all anchors with hrefs
  • :disabled
  • :target - affects specific sections of a page that is targeted through anchor links / fragment identifiers
  • :first-child - Selects every element that is the first child of its parent
  • :last-child - Selects every element that is the last child of its parent
  • :nth-child(n) - Example: p:nth-child(2) Selects every <p> element that is the second child of its parent, this is not exactly the same things as p:nth-child(2n) which selects the 2nd <p> and every 2nd <p> afterwords.
  • :not(selector) - Selects every element that is not a element

Pseudo Elements

Alter the display or behaviour of A CERTAIN PART of the contents inside an element box.

  • ::after - Insert something after the content of element
  • ::before - Insert something before the content of each element
  • ::first-letter - Selects the first letter of each element
  • ::first-line - Selects the first line of each element
  • ::selection - Selects the portion of an element that is selected by the user.
  1. Pseudo Elements API
  2. Pseudo Class API

Selectors

Types of Selectors

Basic Selectors

  • element : target HTML elements types.
    • Example: h1, body, footer, span
  • class : adds semantic meaning to HTML elements. Target any element with a class attribute.
    • one can apply it to many elements on a page, unlike ID’s
    • Global styling
    • Example: .warning, .highlight, .odd, .even
  • ID : Much more specific then class selectors as they have to be unique.
    • A lot of developers actually avoid usage of ID selectors as they are very heavy.
    • Example: h1#title, #main, #overview
  • Descending Selector : are a way to target specific elements based on where they are in conjunction to other elements.
    • They are selectors that are chained together with no limits - Example: Parent > Child + Sibling + Sibling > Child - Example: #main div p span.warning
  • * (Universal Selector) : Matches every element type in your document
    • Can be inefficient for browser performance
    • Example: * - every element on the page
    • Example: div * em - target any em inside any other element that is inside of a div
    • Example: section * p - target and p that is inside ANY element that is inside a section
  • Grouping Selector : A way to select multiple selectors at once
    • Example: h1, h2, h3, h4, h5, h6, .title, { property: value; }

Attribute Selectors

Allow you to match elements based on the presence or value of specific attributes.

  • Syntax: [attribute] { property: value }
    • Example: [class] { color: gold; } - will select everything that has a class attribute, it doesn’t matter what the value is.
    • Example: [href] { color: gold; }
    • Example: p[class] { property: value; }
  • Specifying Attribute values:
    • Find an alt attribute with value ‘img’
      • Example: [alt="img"] {}
    • Is one of the values img of a monkey
      • Example: [alt~="img] {}"
    • Match a prefix
      • Example: a[href^="http://"] {}
    • Match a suffix
      • Example: a[href$=".pdf"] {}
    • Match a partial string, ‘Wildcard’
      • Example: p[class*="book"] {}
        • matches anything with ‘book’ in it, ‘bookkeeper’, ‘booked’.

Selector Specificity

  • Is the point value you can assign to the weight of a selector. The more specific, the more weight and thus general strength of the rules when applied to the cascade.
Specificity Weight
Points Type
10000 (in theory) !important
1000 Inline Style
100 ID
10 Class (or pseudo class)
1 Element
0 * Applies to everything on a page, but has a low weight value.
  • h1 = 1 point
  • h1.title = 11 points
  • h1#mega-title = 101 points

Note: !important declaration will actually overwrite inline styles.

  1. CSS Specificity Calculator
  2. WTF is Specificity

Clearfix

Clearfix is designed to help the browser regain knowledge of the height of containing elements thus clearing collapsed floats.

This usually happens when all the child elements have inline/float properties. For example: div.column { float: left; } add .clearfix to the .wrapper class, and this should be fixed because it’s placing content on the pseudo selectors of :before and : :after. What this does is trick the browser into showing empty content thus figuring out it’s own height.

.clearfix:before, .clearfix:after, { content: “ “; display: table; }

.clearfix:after { clear: both; }


Floats

  • The float property is most commonly used for Page Layout
  • The original purpose of float was to allow text to wrap around an object

  • It’s mostly used in layout where elements IE columns are floated to the left to have them align next to each. If we are using box-sizing: border-box; property, a set of 3 columns at width: 33.33%; will float evenly to the left. If we float them right, the same effect will happen, however the first box will start from the right-hand side.

Video on Floats, atozcss.com


Moduler CSS

It is now a given and essential part of coding CSS.

I should use BEM style class names in my code. I think that has become more and more of a standard.


BEM

  • Block (Parent) .btn {}: Top level abstraction of a new component.
  • Element (Child) .btn__price {}: Elements to be placed inside the Block component.
  • Modifier (Style) .btn--orange {} .btn--big {}: Manipulate the block so that we can style and theme a component without making unrelated changes to the module.
Markup example
<a class="btn btn--big btn--orange" href="http://css-tricks.com">
  		<span class="btn__price">$9.99</span>
  		<span class="btn__text">Subscribe</span>
</a>
  1. BEM 101
  2. SMACSS

CSS3 General

Note: CSS3 is actually a group of a wide number of different specifications. Similar to what HTML5 is. So it’s really just CSS, but tagged with the number 3.

CSS Color Names

These are not appreciated enough IMO.

CSS Color Names API

Gradients

Are pretty complex, use a generator.

Columns

Designed to help display large blocks of text, like a newspaper.

  • Allows you to select how many column: count, width, gap, and many attributes in between.
  • Not supported in IE9 or earlier.
  1. Codepen Example
  2. API Doc
  3. About.com Info

Vertical-Alignment without using the vertical-align property.

  • The vertical-align property is confusing in that it was designed for how things align along a baseline, sub, super, etc. Not the block level from most people try to use it.
  1. Codepen Example Using table-cell property
  2. Using Transform

Shape-Outside

The shape-outside CSS property uses shape values to define the float area for a float and will cause inline content to wrap around the shape instead of the float’s bounding box.

  • It breaks out-side the standard box model and behaves more like traditional magazine layout.
  1. Codepen Example
  2. Moz API

Animations

CSS3 animations allows animation of most HTML elements without using Javascript of eep flash! An animation lets an element gradually change from one style to another. You can change as many CSS properties you want, as many times as you want.

  • @keyframes needed to define the animation. It’s similar to what its like in animation programs. You can even do something like below:
Example
@keyframes example {
	0% {property: value;}	
	25% {property: value;}	
	50% {property: value;}	
	75% {property: value;}	
}
  • animation - to be added to the selector
    • animation-duration - required to show animation
    • animation-iteration-count: infinite
    • animation-name: example - how you bind it to the selector
    • animation-timing-function - ease type stuff
Example
@keyframes example {
	from {background-color: red;}	
	to {background-color: yellow;}	
}

div {
	width: 100px;
	height: 100px;
	background-color: red;
	animation-name: example;
	animation-duration: 4s;
}

More About Animations

Note: CSS Can’t animate Gradients at this time.

  1. CSS Animation API
  2. CSS Animations Aren’t that Tough

Transitions

This applies a transition animation to all elements with the class .button.

.button { transition: 0.25s all linear; }

  1. Duration: 0.25s
  2. Property: (affects) all, color, background-color, width, etc.
  3. Timing: linear, ease, ease-in, ease-out, ease-in-out, custom: cubic-bezier(n,n,n,n)

CSS3 Transitions API

Transforms

Will make the element larger, nudge it up vertically and rotate it by 15 degrees.

transform: scale(1.5,1.5) translate(0, -10px) rotate(15deg);

CSS3 Transforms API

Responsive Web Design (RWD)

  • 3 Pillars of Responsive Web Design
    1. Fluid Grids
    2. Flexible Images
    3. Media Queries

Fluid Grids

  • Formula
    • Target / Context = Result
    • Example when context is .wrapper: 960px;
      • width: 62.5% /* 600/960 */ - 600px / 960px = 62.5%
      • margin: 20px 2%; /* 20/960 */

Fluid Images (Responsive Images)

  • Put images in a <figure> container
  • Give the container a percentage width so that it can be fluid
  • Assign a max-width 100% to <img>

Fills the container width and resizes accordingly. img, iframe, video, object { max-width: 100%; }

Media Queries

If statements for viewport sizes. Best practice is mobile first.

  • The only selector in only screen ... stops older browsers from parsing the remainder of the selector.

Viewport Meta Data

Add this to your website so the viewport respect your media queries.

  • name="viewport" - name of the viewport
  • width=device-width - don’t scale my page down for mobile, I got that covered in my media queries.
  • intial-scale=1.0 - be exactly the width of my device and nothing more.
  • minimum-scale=1.0 - scale appropriate when device is rotated.
  • user-scalable=no = Evil! Doesn’t allow the user to zoom in/out.

#

<meta name="viewport" content="width=device-width, intial-scale=1.0, minimum-scale=1.0">

Viewport Meta Tag more info

Working with HiDPI devices

At this time (2015), for every traditional pixel, the screen will actually render 4. So for every one pixel there is actually 4 pixels and thus a much higher resolution in look and display.

2x images

Twice the width / Twice the height

  • Retina versions should be suffixed, this does make images 3x in size however.
    • Example: [email protected]
  • Using Javascript to load images only when needed.
    • link: Retina.js This will look at the page, find images, and check for versions that have a @2x. suffix.
    • This is a prescribed modifier recommended by Apple.
  • Using the 1.5x method
    • Generally, we are making one image that fits in the middle of each. So you only have to make one image and scale it down for low resolution and bump it up for high resolution.
    • I think I prefer the other method, since your extra work can really deliver a difference and seems more logical. Maybe doing a mix of these two 1.5x + JS solution can provide a gradiented approach.

Retina for background images

  • How to perform a check for retina devices.

#

@media
	only screen and (-webkit-min-device-pixel-ration: 2),
	only screen and (min-resolution: 192dpi) {
	selector { property: value}
	footer { background-image: url('..[email protected]');
}

SVG (Scaleable Vector Graphics)

SVG is badass because it has high resolution for any device and are very small

  • Note: No Support for IE8.
  • Can be used just like any other image.
  • When you inline embed it, you can re-write values on the spot.

Typography

Key Properties

  • font-size
    • default is medium
  • font-weight
    • font-weight: normal; = font-weight: 400;
    • font-weight: bold; = font-weight: 700;
  • font-family
  • font-variant
  • line-height
  • letter-spacing
  • word-spacing
  • text-transform
  • text-decoration
  • text-shadow

  • widow is the last line of a paragraph that APPEARS on its OWN at the TOP of a new PAGE or COLUMN.
    • widows: 3; - Makes sure that there is a minimum of 3 lines at the start of a new page or column
  • orphans - refers to the first line of a paragraph that starts before a page break.
    • orphans: 2; - Ensures that there are at least 2 lines of a paragraph before the end of a page.
    • Orphan has two meanings in typography, it’s also described as a word that sits alone at the bottom of a paragraph.
      • A hack to fix that could be to use a non-breaking space character &nbsp;
        • Example: do&nbsp;not&nbsp;orphan&nbsp;me
        • This way in a responsive design, you won’t get an odd breaking line if you used something like <br />
  1. AtoZ Video

Fonts

@font-face property let’s you add your own fonts to your website.

  • @font-face { font-family: 'font name'; src: ('/path/font.otf'); }
  • a good way to test to ensure fonts are working is to throw a “Times New Roman” after the first value
  • Font Kits exist to serve up mutliple formats for example; .eot, woff, ttf, svg
  • Font Services
    • Google Web Fonts
    • Font Squirrel
    • Typekit
  • Font icons can be used instead of images using the Pseudo selector to place content.

Page Media / Print

CSS can be used to control the styling of things other then website. Digital Magazine, ebooks and print stylesheets. Describes how a document can be flowed into a series of pages.

  • One can actually control quite a bit on printing documents. This is handy to know when a website has to print something out nicely, like a receipt, legal document or etc.

The CSS Page Spec adds functionality for:

  • pagination
  • page margins
  • page size
  • orientation
  • extended generated content
  • page numbering
  • page headers and footers

Tutorial on Page media and Printing

Operators

Calc

Calc can be used for on the fly math calculations in your native CSS.

  • height: calc(100% - 50px);

Codepen Example CSS Tricks Info

Post Processing

Libraries

  1. https://github.com/postcss/postcss
  2. https://github.com/reworkcss/rework
  3. http://pleeease.io/