A new day, and a new section: CSS Foundations
Getting Started with CSS
CSS is a stylesheet language, that describes the presentation of web pages, while HTML describes the structure.
History of CSS – Was introduced in 96 in HTML 4 to solve problems with HTML 3. HTML was never intended to be used for formatting, which made it difficult to do so inside of HTML docs. CSS makes things much easier, because the styles you write in it can be applied to multiple pages. It also allows us to do responsive design. CSS2.1 is the official complete web standard, with parts of CSS3 implemented, which simply extends 2.1. It added rounded corners, gradients, transitions and animations, multi-columns and flex box.
CSS Cascade decides which styles are applied, and to which elements. 3 main steps:
1. Importance – depends on the origin of the stylesheet. The user agent stylesheet is the one the browser applies by default. The user stylesheet contains styles set by the user, which are predefined and can be different than the browser’s default styles. These are often used for accessibility, for people with special needs. The Third source is the author stylesheet which contains the CSS we create to style the html page. By default, the author style sheet has more importance than the user or agent ones.
2. Specificity – determines which css styles are applied by the browser. This means: if two selectors match the same element, the one with the highest specificity will take precedence.
3. Source Order – is important because the cascade assigns a priority to CSS styles based on the order they appear.So if there are two selectors for an element with the same importance and specificity, the one that comes later in the stylesheet will be applied.
Once these three things have been taken into consideration, each CSS rule is assigned a weight that determines which property will be assigned to an element. Learn more on the specifics here.
CSS inheritance – means that an HTML element’s style values are copied from its parent elements. For example, if the body element of the page’s font color is set, that font color will be inherited by its header and paragraphs elements, unless we specify otherwise.
A CSS Rule is comprised of two main parts, the selector and the declarations. The selector is what targets the HTML elements, and you can have multiple selectors in a rule. The declarations specify the styling, and consists of the property name (which says which value we want to change) and the property value (which is what we want to set it to). You can have as many declarations as you want, you just need to separate them with a semicolon.
Three methods to apply CSS to a page:
inline styles – mix content with presentation, because the css is applied directly to the html element, which is not recommended. You use the style attribute inside the html element you want to style. These are at the lowest level possible of the cascade, so they will override any styles declared by the internal or external stylesheets. They are not considered good practice and should be used sparingly, because to make styling changes, you need to go directly into the markup, so you’re not separating content from presentation.
<body style=”background-color: blue;”>
internal can be okay for quick html/css mock ups, or for temporary styles. These are embedded in the head section and are defined using the <style> element. Downside to using this is that because the styles are on the page, they are required to be downloaded each time that the page is loaded by the browser. This also will require a lot of duplication between pages and would be a pain to change the css for an entire website.
external – can change the styling of all pages of an entire site with just one file. You link the html to the css with a link element in the head section. You need to at least use the rel and the href attributes. Another advantage is the stylesheet is oftentimes cached by the browser, which means it’s saved by the browser, so it only needed to be downloaded once.
The @import rule is another method of using an external stylesheet, which can be used in an internal stylesheet. Shares advantage of maintenance efficiency and browser caching. The drawback to using this is performance – as each import statement is a new request to a server.
You can also import a stylesheet, from within a stylesheet. It must be listed at the top of the stylesheet for it to work, and you only need this part: @import ‘more-styles.css’. This might be useful if you’ve split up your CSS into multiple sheets to make it easier to manager (like for a large site).
Selectors are patterns that allow us to target html elements and apply styles to them. When you define one in your stylesheet, you’re instructing it to match every instance of that element in the html.
Universal selector – selects every element on the page at once, and applies the styles we set. Very powerful, takes precedence over all other selectors. It is simply an asterisk: * It’s worth noting that inheritance will not work with the universal selector, because it trumps any form of inherited styles.
Type selector – what’s used to select an element on the page. Also called an element selector, because only html tags are used as the selector. Examples: h1, p, body, etc.
Descendent selectors – are a combination of type selectors. It selects an element that’s a descendent of another element. Simply write the parent element, then it’s child element. In the example below, only span elements inside of h1 elements will be selected and styled. It’s worth noting that the space between them is considered a combinator (the descendent combinator).
Classes and id’s let us target elements based on their id and class attributes. The difference between them is that id’s are unique, and are used to identify one element on the page, and classes can be used for multiple elements.
It’s a good idea to give classes and id’s meaningful names that explain what they do, and what their purpose is.
Classes are selected in css by using a period and then the class name.
You can set multiple classes for an element, simply put a space between each one.
You can do descendent selectors with classes as well.
id selector – an element can only have one id at a time (unlike classes), and the page can only have one element with that id name. You create them using the # symbol. #idname. Id’s also have browser functionality, and can be used to make landmarks for anchor elements, so you can link to a certain part of a page.
An element can have an id and a class applied to it, but the id has higher specificity, so any of its styles will always be applied over the classes. So, make sure not to share properties between classes and ids.
Selector groups are css rules containing two or more comma separated selectors sharing the same properties or values. This minimizes css and makes it more maintainable, because you’re not just repeating lines of code. You add commas between each selector, except for the very last one, or the entire rule will be ignored by the browser.
DRY (Don’t Repeat Yourself) – common practice in web development. So, if you have multiple elements with the same property values, it’s good to group them together for those so you don’t have to repeat the code. Before and after example written below, look how much less code is written for the same outcome:
Modules aka Components – instead of having a bunch of classes like above, you can group them together into one class, and then use multiple classes on your elements for the same effect.
Combinators explain the relationship between two or more selectors. They can be a space, a greater than sign, a plus sign, or a tilde (~).
Greater than sign (>) is referred to as a child combinator, and selectors that use them are called child selectors, because they target things that are direct children of the parent elements listed. Do NOT confuse this with the descendent selector covered earlier. If you type “.main > a”, it will only apply styling to a elements that are direct children of elements with the .main class. If you were to instead type “.main a” the styling would be applied to every anchor element inside .main class elements.
Plus sign (+) is referred to as an adjacent sibling combinator, and selectors that use them are called adjacent sibling selectors because they target an elements next sibling on the page. So, “h2 + p” would target only paragraph elements immediately following h2.
Tilde symbol (~) is referred to as the general sibling combinator, and selectors that use them are called general sibling selectors. So, “h2 ~ p” means that the styles will be applied to every sibling paragraph element following an h2.
Attribute selectors allow us to target elements based on a given attribute or value. A basic attribute selector consists of a name, surrounded by square brackets. In the example below, only elements with a class attribute will have the styling applied. Keep in mind, attribute selectors have the same level of specificity as classes and pseudo-class selectors.
Now, if you wanted to only select the anchor elements with the class attribute, you simply write this (with no space between them): “a[class]”.
If you only want to target attributes with a specific value, you simply add an =value into the square brackets: [class=”foo”]. Now, this is another way of targeting classes with css, but we should avoid this way because it makes the browser do a little bit more work. It’s better to do it like this: .classname
Example of how this could actually be useful: Let’s say you want to style a form input that was a text type, or the submit button. You could do something like this:
pseudo-classes are similar to classes, the difference being that they are not explicitly defined in the mark up and don’t appear in the source code. Unlike most selectors, they select elements dynamically based on user actions, the element’s state and more.
link pseudo-classes let us style links based on whether they’ve been clicked on, or if you’re hovering over them. You add them by putting a colon and then the one you want after the anchor selector (with no space between them).
a:link is for links that haven’t been clicked yet. Worth noting this will only target anchor attributes that have the href attribute.
a:visited is for links that have been clicked.
User action pseudo-classes get applied based on the interaction of the user with the element.
a:hover is applied when a user hovers over an element. It’s worth noting that the hover pseudo-class can be applied to ANY element, like divs, uls, p, etc.
a:active is applied when the element is being activated by a user. An example is when a user presses the mouse to click on a link or button. But, once they stop clicking, the element is no longer considered active. Like hover, active can be applied to any element.
a:focus is only applied to interactive elements like links and form elements. The styles are applied as soon as the element has received focus, which happens when a browser discovers that a user is ready to interact with an element. For example, when a user clicks inside a text type form field, that field is said to have focus.
If you want to apply focus to links and form elements, simply write it without something before the colon :focus. You can do this for any of the pseudo-classes if you really wanted to.
Basic structural pseudo-classes – let’s you target things based on their position in the HTML document. Can write more efficient CSS with this.
li:first-child – will select and apply styles to the list item element that is the very first child in the ul parent element. This can be for any child element, not just li’s
li:last-child – will select and apply styles to the list item element that is the very last child in the ul parent element. Example of real world use: let’s say you had a bunch of list items that had a bottom border, but didn’t want to have one for the last one. You could set use the property border: none; with this pseudo-class to do that, rather than having to make a class just for that list item (and have to put it in the markup).
span:only-child – for when a parent element has only one child element, it will select and style that element. It the parent has more than one child (and therefore the child element has a sibling), this won’t apply the styling. In span:only-child, it will only select span elements if they’re the only child element in the parent element.
substring matching attribute selectors – allow you to get really specific, and target pieces of those attribute values, like certain letters or words. Those pieces are called “substrings” These have strong browser support, even for IE7. They’re the three listed below.
“begins with” attribute selector – it targets elements whose attribute value begins with the value we specify. You do this with the carrot (^). In the example below, we’re targeting anchor elements who have the href value that begins with “http”. Useful example: if you wanted to style only mailto links, you could write a[href^=”mailto”].
“ends with” attribute selector – it targets elements whose attribute value ends with the value specified. Uses the dollar sign ($) before the equals sign. Useful example: if you wanted to have different styles for different file types to download, you could right a[href$=”pdf”]
“contains” selector – targets the element whose attribute value contains the substring we define, anywhere in there. Uses the asterisk (*) before the equal sign. So, img[src*=”thumb”] would target any img element that has the word “thumb” anywhere in the value for its src attribute.
:nth-child pseudo-class – allows you to target elements between the first and last child elements. Uses a function like syntax that allows a value or argument to passed inside the parentheses. You can use the keywords odd or even to select every other child element. Or, you can just write the number integer (like 3, 6, or 9), you can select that number element.
You can also use expressions to select different combinations of child elements. The basic expression syntax looks like this :nth-child(an+b). The values a and b are always represented by numbers, and the n value never changes. The b value is an offset value that determines the first value selected. The a value determines the cycle of values to be selected, after the first one has been selected. So, (2n+3) means that it will start with the 3rd child element, and will select every second element after that. n is telling the browser to select every second element after the 3rd one.
If you have a=1 (so 1n) in your expression, you can just write n, because it means the same thing. If b=0, you can omit the b value, because (2n+0) is the same as (2n). Finally, if a=b, you can omit b because (3n+3) is the same as (3n).
You can also use negative values. So, (-n+5) will select the 5th list item first, then all the list items before it.
:nth-last-child structural pseudo-class works just like nth-child, only it starts counting from the last child element. So, li:nth-last-child(-n+3) would select the 3rd to last child element, and every one after that.
:nth-of-type pseudo-class targets an element based on its position in its parent element, but only if it’s the type of element specified. This is more flexible if we want to make sure we’re selecting the same type of element, no matter where it is in the parent, or what elements appear before it. So, div:nth-of-type(even) will select the even divs, based on on how many divs there are, ignoring any non div sibling elements that may be between them. You can put the same things in the parentheses as nth-child pseudo class above.
:nth-last-of-type works exactly the same, only it starts counting from the last child element of that type.
:only-of-type pseudo-class is good for selecting the only child element of that type in the parent. So if you wrote p:only-of-type, it wouldn’t work if you had two p elements in the parent. Also, for these, you don’t need parentheses, which makes sense.
:root selects the element that is the root of the document, which will usually be the HTML element. Why use :root over the html selector? Because :root has higher specificity because it’s a pseudo-class.
:target allow us to target elements only if the #(hash) of the url linking to it matches the # listed in its id. More here. If you set this up, the element the link takes you to will take on those styles. Fragment identifiers are href values that have a hashtag (#) followed by the identifier name, that matched an identifier on the page. These are used for setting up links to different parts of the page using ids.
:empty lets you target elements that contain no child elements or content whatsoever. So the only things that would be affected would be something like <div></div>. A good use case for this would be when a results field or element returns empty with no content – you can use this to notify the user of that issue.
:not() is a negation pseudo class, because it selects everything except the element specified. You use parentheses and arguments for this one. So to select every div that is not empty, you could write div:not(:empty). You can also use attributes and their values in the argument, but make sure to put them in brackets. So, to select all divs, except for one with the id value of s1, you’d write div:not([id=”s1″])
UI element states pseudo-classes target elements based on certain user interaction states. This is why they’re most commonly used for styling form elements.
:enabled selector selects ui elements that are in an enabled state, such as a button or a text field. When a form element is enabled it can be active and gain focus. So it can also be selected, clicked on and gain text input. So if you type what’s below, all text elements will have yellow background, because they’re all enabled by default.
:disabled selector selects UI elements like buttons and form inputs that are in a disabled state. When a form element is disabled, it cannot be selected, clicked on or accept text input. disabled is a boolean attribute that can be added to input elements. A boolean attribute is one where you just have to write it in the opening tag, it doesn’t need to be set to a value. <input type=”text” id=”username” name=”username” disabled>
:checked pseudo-class lets us style UI elements that are in a checked state, like a text box, or a radio button. In the (somewhat surprisingly advanced) example below, we start off with input elements who have the attribute “type” set to “radio”, in a state of checked, then use the adjacent child combinator (+) select the immediate label sibling element after it.
Pseudo-element selectors – there are four types, they help to keep our markup cleaner, because they can target virtual elements that are not defined in the markup or appear in the source code. The easiest way to remember the difference between pseudo-classes and pseudo-elements, is pseudo-classes target actual elements that in a certain state, while pseudo-elements let us style certain parts of a document that don’t always exist as elements, or we can’t really target with a simple selector.
You’ll see pseudo-elements written with two colons (::). It would work with just one, but you do it this way to distinguish pseudo-elements vs classes.
::first-line targets the first line of the element. So if you wrote p::first-line, it would select the first line of text rendered by the browser, and the amount of words selected might change depending on the width of the browser.
::first-letter pseudo-element will select the very first character of the first line of text. This commonly used for graphical effects, like the drop cap, where the first letter is enlarged to drop down the text by two lines. If you’re using a pseudo-element on a class, there should be no space between the class and the colons.
::before and ::after let us insert virtual elements before and after an elements content. These are visible to a user and styleable by CSS, but are not visible in the source code. So we can add to our html from our CSS. This is called generated content. They both work the same way, only one inserts things before, and the other after.
In order for ::before or ::after to work, in your rule you must use the content property, or you won’t be able to generate any content. At the very least, it must contain an empty set of quotes as its value. The \2706 is the unicode icon for a phone.
You can also insert images using the content property with url(). However, you don’t want to use quotes for this, as this would turn it into a literal string, which inserts the actual text written in the quotes as the content instead of the image. In the example below I used and absolute link but you can also use relative ones.
Another good feature of pseudo elements – we can use simple functions to return generated content based on an element’s attribute. In the example below, we take the value of the attribute specified (in this case title), and places it as text content next to the element. Note, that you don’t put quotes around attr() either.
We mentioned you can also just have content set to empty quotes. You can use this to make shapes. In the example below, we made a selector group by putting a comma in between them.
One of the most important things to keep in mind about pseudo elements is that the generated content is not exactly inserted before and after the actual element, it’s actually inserted into the element as child content. So in the example above, the circles aren’t before or after the element, they’re part of it. You can see this below when we applied a border to it.
Values and Units
Every css property has a value it can accept, like a predefined keyword, a url or number. For measurements, the values can either be relative, or absolute.
Absolute length units are fixed in relation to each other. They represent a physical measurement and are only useful when the physical properties of the output medium are known. Examples include cm, mm, in, picas, points and pixels.
cm, mm and in (centimeters, millimeters and inches) are not commonly used or intended for web design, because they’re highly dependent on the output medium, and can vary greatly based on screen size and resolution.
pc and pt (picas and points) are commonly used in print, but not really intended for web or screen design.
px (pixel) is one of the most commonly used units. Indicates one point on the virtual grid. They allow us to position elements precisely on a page, and will not scale regardless of the browser size or the user’s resolution. It’s equal to 1/96 of an inch and is the smallest unit in screen based design, because it’s the smallest point a screen can physically display.
But because pixel densities are increasing and display resolutions are varying widely, the definition of a pixel has changed. Instead of every measurement being based on hardware or device pixels by relating their physical units to physical measurements on a screen, pixels can also anchor their measurements to an optically consistent reference unit called the reference pixel, the current standard for all pixel based measurements. It defines the visual angle of one pixel on a device with a pixel density of 96 dpi. This will help things look consistent in all view situations regardless of pixel density. Learn more at W3C.
Except for pixel units, web designers avoid absolute length units. For print it’s fine though, since the size of the page would be known.
Relative length units specify lengths that are relative to another length. These are useful for screen based design because they scale on multiple screens and devices with consistent results.
ex units is equal to the current font’s x-height, which is oftentimes the height of its character x. Different fonts usually have different fonts for ex. These do not resize with the window, but they are sized in relation to another value. If you change the pages font size, it will change what the x-height is.
em units are popular units of measurement that are equal to the computed value of the font size property of the element on which it’s used. One em is equal to the inherited font size. If we haven’t set the font size anywhere on the page, then it goes off the browsers default font size setting, typically 16px. Very useful unit in CSS because it can adapt automatically to the font the user chooses to use.
Let’s say you want to get a font size of 12px with em’s. To do this you take the size you want (12) and divide it by the default font size (16). In this case that gives you .75em.
Same concept for using ems for width values. If you set the width of an element to 30em, it will be the width of 30 x 16px(the default font size of the page), so 480px.
There is a compounding effect in nested elements. So in the example below, because we specified a font size for the p elements div parent element of 2em. This would be 32px, and because in the p element we specified a font-size of 1.2em, this is now based off of the div parent elements font size (32px), rather than the page’s default of 16px. This can be troublesome depending on how many font-sizes you’ve defined in the page.
To help prevent this, you can use a relatively new unit – the rem unit (root em unit). This always uses the font-size of the root element of the page as its reference, which is usually the html element. If you define the font-size for the root element, then all the rem units on the page are relative to that font size. IE9 and up have support for this unit.
Viewport-relative units – were recently added for resizing elements. They are vw, vh and vmin. They eliminate the dependence on parent elements, and are instead based off of the viewport size. Each units value is equal to 1% or 1/100 of the viewport size. The viewport is the part of the page that the user can currently see. So, when that is resized, the calculated values of these units change to resize the specified elements relative to the width and the height of the viewport, or to the smallest of the two sizes. They’re not that common yet, but will be soon once browser support increases, only currently support in IE9 and up, Chrome 20 and up, Safari 6 and up.
vw (viewport width) – unit is equal to 1/100th, or 1% of the viewport width. So, setting the width:15vw; would make it 15% of the viewport’s width.
vh (viewport height) – unit is equal to 1/100th, or 1% of the viewport height. So, setting the height:15vh; would make it 15% of the viewport’s height.
vmin (viewport minimum) – unit is equal to 1/100th, or 1% of the minimum value between the height and the width of the viewport. So if the width of the viewport is smaller, it will go with that, and vice versa with the height of the viewport.
PROTIP: if you’re ever unsure whether or not you can use a property or something else for a certain browser, go to http://caniuse.com/
Numerical and Textual Data Types
auto is the default value for certain properties like height, width and z-index. It means the browser automatically calculates those values. In the example below, because div is a block level element, with a specified width of 700px, the left and right margins will be set to equal.
inherit can be used on any property to explicitly specify that the value of the property should be the same as its parent element’s. For example, anchor elements by default do not inherit color values unless specified. Normally you shouldn’t do this (because it’s confusing), this was just an example of how it works. List of all properties that accept the inherit value here.
initial value is the value that’s designated as the properties initial value, the one it would have if no styles were applied. For example, for the color property it’s black. Chrome and Safari support this, but IE doesn’t and for FF you need to use -moz- beforehand.
Quoted strings – In the example below we use an ::after pseudo-element to add some text after the div. After the content property we add a string in between the quotes, which is what will appear on the page. If you want to have double quotes inside your quoted string, you need to escape them by putting a backslash before it. If you want to use the backslash character as part of the string, you’ll also need to proceed it with a backslash to escape it. These same conventions also apply when using single quoted strings.
URLs – to set a property to a url, simply write url(); The url specified can optionally be enclosed by single of double quotes, and can contain whitespace before or after it.
Numeric value types can be Integers or Real numbers. Integers are made up of a combo of the digits 0-9, and real numbers can either be an integer, or one that contains a decimal point. Either type can have a negative sign to be negative. These work in the reverse way that positive values work. Only a few properties can accept a negative value, some of these include margin, background position, text indent, and position for properties for top, right, bottom and left.
Decimals can be added to your number values.
Percentages can be used, just write a number followed by the percentage sign. They’re always computed relative to another value, usually a length unit. Common properties that use these include: width, margin, padding and font-size. If you were doing width, like width: 50%, it would make the width 50% of the width specified for its parent element. For fonts, the size of the font will be related to the parent elements font size.
Color Values can be described in several different ways in CSS.
Keyword – one of 16 basic keywords that define common colors (red, blue, green, etc). There is also a list of extended color keywords supported by browsers. These might contain a couple words, but are written together with no spaces, like lightblue or sandybrown. For a full list of these colors, see here at W3C.
Hexadecimal notation is another way to describe colors. A hex value is a combination or Red, Green and Blue color values. You specify it with a hex (#) sign, followed by six hex characters, which can be zero through nine then a through f. So, for #ff0033, ff is the red value, 00 is the green value and 33 is the blue value. Each pair value van be abbreviated if the value if the same, so we could rewrite this as #f03.
RGB method – uses functional notation to specify colors in terms of a mixture between red, green and blue values. 0 is the minimum value we can use, and 255 is the maximum.
RGBa method – You can expand the RGB model to allow for the alpha channel a, which will allow you to specify opacity. 0 would give us full transparency, and 1 would be completely opaque, which means not transparent or see through at all.
HSL method is similar to RGB in that you declare three values to determine color. In this case it’s Hue, Saturation and Lightness. Hue is represented as an angle in the color wheel, measured by degrees. If you view this color wheel it will make more sense. You can play with an interactive one here.
For the Saturation value, zero percent is completely desaturated, aka grey-scale, and 100% fully saturated, or full color. The Lightness value is also done with percentages. 0% lightness is black, 100% whiteness is white and 50% is normal.
Like RGBa, you can use HSLa to add an alpha channel and adjust opacity. They’re both widely supported in the major values. HSLa is better when you need to adjust colors on the fly, because you know how each value change will affect the color.