Lecture overview¶
- CSS syntax: selectors, properties and values
- CSS: borders and colors
- Using classes and id:s
- CSS Box model
- CSS Layout
- legacy methods vs new methods
- display models
- positioning
- floats
- flexbox
- If we have the time
- Introduction to RWD (Responsive Web Design)
- Typography
HTML5 template¶
<!doctype html>
<!-- Language information for better search engine and browser support -->
<html lang="en">
<head>
<!-- Text encoding used by this text file. -->
<meta charset="utf-8">
<title>Document 1</title>
<!-- File that contains stylesheet. Multiple css-files can be linked to. -->
<link rel="stylesheet" href="style.css">
<!-- File that contains JavaScript for page. Multiple JavaScript files
can be used. They will be loaded in written order. -->
<script src="script.js"></script>
</head>
<body>
<!-- page content here -->
</body>
</html>
Adding a class to a HTML element¶
<tag class="name-of-class"> ... </tag>
- Why? More flexibility for selecting parts of the DOM to apply a style to, or to manipulate with JavaScript
- Example: we have different kinds of paragraphs to which we want to apply different styles (e.g. font face).
- Assigning different classes to different paragraphs allows us to apply different styles to paragraphs with different classes.
Adding an id to an element¶
- Adding an id to an element allows us to target a specific element e.g. to apply a style or some kind of interaction.
- BUT it is a better strategy to be as general as possible with applications of styles/interactions.
Inline CSS
<!doctype html>
<html>
<head>
<title>Inline CSS</title>
</head>
<body style="background-color: lightblue;">
<h1 style="color:navy;margin-left: 20px;">This is styled inline</h1>
<p>This is a paragraph.</p>
</body>
</html>
Internal CSS¶
<!doctype html>
<html>
<head>
<title>Internal CSS</title>
<style>
body {
background-color: lightblue;
}
h1 {
color: navy;
margin-left: 20px;
}
</style>
</head>
<body>
<h1>This is styled internally</h1>
<p>This is a paragraph.</p>
</body>
</html>
External CSS (what you should use)
- external_css.html:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="mystyle.css">
<title>External CSS</title>
</head>
<body>
<h1>This is styled externally</h1>
<p>This is a paragraph.</p>
</body>
</html>
- mystyle.css:
body {
background-color: lightblue;
}
h1 {
color: navy;
margin-left: 20px;
}
So what were we actually doing here?¶
CSS (Cascading Style Sheets)¶
- CSS specifies
- visual style
- layout
- HTML elements inherit CSS properties from their ancestors
- e.g. the value of the
font-family
property for the<body>
element is inherited by the<p>
element.
- e.g. the value of the
- "Cascading" comes from how priority is determined if more than one style declaration can apply to a given element.
- Normally, a multitude of CSS source files are used and a browser will search through these in order of priority to find which style to apply.
- We also often separate layout and style into different files
Aspects of style¶
- Colors and borders, e.g.
- background color/image
- borders around elements
- Typography, e.g.
- font, font size
- line height
- Size of elements
Aspects of layout¶
- Positioning of elements
- Interaction between elements (e.g. what happens when two elements want to use the same space)
- Size of aggregated elements
The style sheet¶
- Plain text file
- A collection of style specifications combining a selector and a set of rules.
- The selector specifies which portions of the DOM should be affected.
- The rules specify how those portions should be affected.
- A HTML document can link to one or more stylesheets.
- Style specifications are evaluated in series from the top.
- Later specifications can overrule previous specifications.
- This is the cascade referred to in the name.
External CSS (what you should use)
- external_css.html:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="mystyle.css">
<title>External CSS</title>
</head>
<body>
<h1>This is styled externally</h1>
<p>This is a paragraph.</p>
</body>
</html>
- mystyle.css:
body {
background-color: lightblue;
}
h1 {
color: navy;
margin-left: 20px;
}
CSS Rule Syntax¶
Syntax¶
/* This is a comment */
body {
font-family: Times, Serif;
font-size: 16px;
padding: 0px 0px 0px 0px;
}
h1 {
font-family: Helvetica, Sans-Serif;
font-size: 32px;
}
Filepaths in HTML and CSS¶
- Unless otherwise specified, all filepaths are relative to the current file.
/
means the root of the web site, i.e. for./
means current directory../
means go up one directory
I've used CSS before and it is extremely confusing and painful!¶
- Yes, it can be.
- Learn to work with the inspector in your browser to find which rule is applied to the element that isn't behaving itself.
- Frameworks or other parts of your toolchain might overrule parts of your custom CSS unless you provide the correct templates or configuration files.
- Perfect example, my slides.
- Some properties might have no effect depending on other properties. Like how the
display
property affects thewidth
andheight
attributes.- The
width
andheight
properties apply to an element if itsdisplay
property is set todisplay: block
, but not if set todisplay: inline
.
- The
- CSS that you have built yourself is generally MUCH easier to get and keep straight than modifying something generated by a complex chain of tools.
- Take a deep breath. You will develop an intuition and a workflow.
Examples of properties¶
Some style properties of HTML elements¶
font-size
: size of fontfont-family
: name of fontline-height
: height of linnewidth
: width of elementheight
: height of elementmargin
: distance to next elementpadding
: distance to element contentcolor
: font colorbackground-color
: background color of elementborder
: border style of element
Size¶
Size properties¶
width
height
- related properties:
max-width
,min-width
,max-height
,min-height
The <length>
data type¶
- Absolute vs relative units
- Relative units vs relative units
- https://developer.mozilla.org/en-US/docs/Web/CSS/length
- https://wpengine.com/resources/choose-css-unit-create-better-site-layouts-how-to/
CSS Rule Repetition¶
Selecting your selector¶
- Targeting a group of elements
- "select all paragraphs and list items"
- Targeting adjacent siblings
- "select all paragraphs that directly follow a heading"
- Targeting descendants
- "select any image that is inside a
<article>
"
- "select any image that is inside a
- Targeting children
- "select all first level list items in unordered lists with the class 'toc'"
Selectors¶
- single element type - apply rule to all elements of that type, e.g. use the color red for all paragraph elements
p { color: red }
- class - apply rule to all elements with that class. All class names are prefixed with a
.
.card { width: 25%; }
- element and class, all elements of a specific type with a specific class, e.g. all paragraphs with the class "preamble"
p.preamble { font-weight: bold; }
Attribute selectors¶
- Select all HTML elements with a specific attribute
[attr]
- Select all HTML elements with a specific attribute + value
[attr=value]
- Select all HTML elements with a specific attribute with a value that contains value
[attr~=value]
Selector combinators - Adding hierarchy to a selector¶
- Descendant combinators - general ancestor hierarchy. E.g. paragraphs that are descendents of
.card
elements that are descendants of.main
elements.p
does not have to be a child of.card
i.e. it can be a grandchild or a great grandchild.
.main .card p
- Child combinator - direct children. E.g. paragraphs that are direct children of
.card
elements.
.card > p
- Adjacent sibling combinator. E.g. paragraphs that are adjacent siblings (follow directly) to
h2
elements.
h2 + p
Combinators¶
/* Select all li elements that are descendants of (i.e. nested within) a nav element. */
nav li {
color: #F00;
}
/* Target all p elements that are on the same level as a h1 and follow a h1 */
h1 + p {
font-weight: bold;
}
/* Target all p elements that are direct children of a div */
div > p {
border: 2px solid #000;
}
Select muliple elements¶
/* Target all h1, h2 and h3 element */
h1, h2, h3 {
border: 2px solid #000;
}
Pseudo classes¶
- Pseudo-classes are keywords that are added to a ordinary selector, denoted with a
:
(colon). - https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes
- Some categories of pseudo-classes:
- Element display state pseudo-classes, e.g.
:fullscreen
only selects an element when it is displayed in fullscreen mode. - Input pseudo-classes, used with form elements, e.g.
:read-only
only selects an element if it cannot be changed by the user. - Location pseudo-classes, used with links and link-targeted elements, e.g.
:target
only selects the one element that matches the URL's fragment, if any. - Tree-structural pseudo-classes, relates to the tree structure of the HTML, e.g.
:only-child
only selects elements that have no siblings - User action pseudo-classes, depends on user input, e.g.
:focus
matches the element that currently has focus.
- Element display state pseudo-classes, e.g.
Pseudo selectors, examples¶
- Select images when the mouse is on top of them:
img:hover
- Select
a
elements (i.e. links) that have been visited:
a:visited
- Select the first of a group of sibling elements. e.g. select the first
p
element in everydiv
:
div p:first-child
- Select the last of a group of sibling elements e.g. selects the last
p
element within any container:
p:last-child
Custom properties
(CSS variables)
We can declare custom properties for later use¶
/* custom properties must start with -- and are case-sensitive */
/* define the custom property --half-gutter-width for the whole CSS document */
:root {
--half-gutter-width: 32px;
}
/* we can then use the custom property in other declarations using the var() function */
.sidebar {
margin-left: var(--half-gutter-width);
margin-right: var(--half-gutter-width)
}
CSS Reset
eliminate browser differences
CSS Resets
- Browsers come with default stylesheets.
- Some default styles differ between browsers.
- CSS Reset: CSS that sets the style of these properties to known values ~ common baseline style.
- Important! All assignments for this course should use Eric Meyer's CSS reset!
- Eric Meyer's CSS reset from 2011
- https://meyerweb.com/eric/tools/css/reset/reset.css
- Normalize.css
- http://nicolasgallagher.com/about-normalize-css/
- Reboot, Resets, and Reasoning
- https://css-tricks.com/reboot-resets-reasoning/
Classes and id:s
More about classes and id:s
What is a class? When should I use it?¶
- Elements can be assigned one or more classes
- More than one element can be assigned the same class.
- Use classes for recurring components of your web page.
- The prefix
.
(dot) is used to in front of class names in CSS selectors. - HTML start tag examples:
<div class="box">, <div class="box green-bg">
- CSS selector examples:
.box, div.box, div.box.green-bg, green-bg
Example of using multiple classes
.wrapper {
width: 960px;
}
.green-bg {
background-color: green;
}
.yellow-bg {
background-color: yellow;
}
.blue-fg {
color: blue;
}
.box {
border: 1px solid purple;
width: 100px;
height: 100px;
}
<div class="wrapper">
<div class="green-bg box">Box 1</div>
<div class="green-yellow box">Box 2</div>
<div class="box blue-fg">Box 3</div>
<!-- If multiple classes conflict, the order of their specification in the CSS file governs priority -->
<div class="green-bg yellow-bg box">Box 4</div>
</div>
What is an id? When should I use it?¶
- Elements can be assigned a single id
- An id can only be assigned to a single element in a HTML document.
- The prefix
#
(octothorpe, hash sign, pound sign) is used in front of id:s in CSS selectors. - HTML examples:
<div id="footer"> ... </div>
<h1 id="main-heading"> ... </h1>
- CSS selector examples:
#footer, div#footer, h1#main-heading, #main-heading
Selectors using classes and ids¶
.infobox {
font-family: Helvetica, Arial, Sans-Serif;
font-size: 0.9em;
background-color: #999;
color: #000;
border: 2px solid black;
}
#menu {
background-color: #000;
color: #FFF;
}
Recommendations for writing CSS¶
- Try to be as unspecific as possible in order to be able to reuse code.
- Less rules can be overridden by more specific rules when needed.
- Avoid relying on ID:s (for styling). Try to use classes or paths, as these make it possible to reuse styles, i.e. "Don't repeat yourself." (DRY)
- But don't over-generalize, i.e. "Keep It Simple, Stupid" (KISS), and...
- Avoid creating new CSS rules until you actually need them, i.e. "Ya Ain't Gonna Need It" (YAGNI).
The CSS box model (block context)¶
Specifying an element's padding¶
- If the element should have the same padding in all directions:
padding: <value>;
- If not, then as one declaration with the value for each direction comma-separated (the order is clockwise starting with top):
padding: <top value>, <right value>, <bottom value>, <left value>;
- or, as separate declarations:
padding-top: <top value>;
padding-right: <right value>;
padding-bottom: <bottom value>;
padding-left: <left value>;
- Rules for margin and border work similarly.
Colors and borders¶
Specifying color: RGB¶
- Additive color model with the components Red, Green, and Blue (in that order, always).
- Each color component specified as
0-255
(decimal),00-FF
(hex), or0-F
(hex shorthand for when both hex digits are the same, e.g.77
→7
orBB
→B
). - Black
rgb(0, 0, 0)
or#000000
(or#000
in 3-digit shorthand)
- White
rgb(255, 255, 255)
or#FFFFFF
(or#FFF
in shorthand)
- Purple
rgb(128, 0, 255)
or#8000FF
(can't be expressed in shorthand)
background-color, color¶
- Headline with white text on petrol blue background:
h1 {
color: #fff;
background-color: #2c7987;
}
CSS Borders¶
- Certain elements can have a border
- A border has the following properties:
width
style
color
CSS Borders¶
- Shorthand declaration
border: <width> <style> <color>;
- Specific properties
border-style
,border-width
,border-color
border-top
,border-right
,border-bottom
,border-left
border-top-style
,border-top-color
, etc.
Layout approaches in CSS¶
- Normal flow (flow layout) + positioning
display: block
|inline
|inline-block
position: static
|relative
|fixed
|absolute
|sticky
- Floating elements (legacy use for layout)
float: left
|right
|none
- Flexbox layout (parent manages children for a column/row based layout)
display: flex
- Grid layout (define a parent grid an place children within the grid)
display: grid
How to layout a page?¶
- Break the page down into structures
- Ignore the inner structures, work from big to small
- Flexbox will solve most of your problems
- Flexbox can be arranged in rows or columns
- Think in rows
- and sometimes also in columns
- Flexbox can be arranged in rows or columns
- Use background-colors to identify your containers
- Fill with dummy text or set min-heights
Can I always use Flexbox?¶
- Almost, but...
- The default, or normal flow for most elements is
display: block
|inline
+position: static
- In CSS, each element
- exists inside a layout context
- provides a layout context for the elements in contains
- Even if you layout a set of elements using flex or grid, anything inside those elements will still follow the normal flow unless otherwise specified.
- In CSS, each element
- Flexbox and grid layout can be very useful but cannot solve everything.
- The default, or normal flow for most elements is
- I.e. understanding normal flow + positioning is still a necessity
Normal flow¶
- Normal flow is the default formatting context.
display
values for normal flow:block
inline
inline-block
- The
inline
context is “in line with text” with the generic inline element being<span>
(cannot have width/height). - The
block
context is “outside text” with the generic block element being<div>
. A block element occupies an area from left to right and has a width and height. - The
inline-block
context is a block in line with text (can have width/height) - https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Normal_Flow
The display property¶
/* The formatting context is set using the display property */
.infobox {
display: block;
}
.question {
display: inline;
}
.wrapper {
display: flex;
}
Inner and outer display types¶
- Outer display type: how the element will be displayed inside other elements
display: block
|inline
- Inner display type: how child elements will be displayed
display: flex
|grid
- For a complete list, see
Five positioning types¶
position: static
position: relative
position: fixed
position: absolute
position: sticky
z-index: <number>
- z-index only affects position elements.
- See
Layout using positioning¶
static
: Blocks are statically positioned by default.
position: static
relative
: Relative positioning adjusts the static position relatively
position: relative;
top: -20px;
left: 20px;
Layout using positioning¶
fixed
: A block can be fixed to a position relative to the viewport
position: fixed;
bottom: 0px;
right: 0px;
absolute
: An element can be given an absolute position relative to the nearest positioned ancestor (e.g. a ancestor withposition: relative
)
position: absolute;
top: -20px;
left: 20px;
Layout using positioning¶
- Relatively positioned until scrolled to a threshold point
- "when the element reaches 30px from the top / 30px from the left, stick to that position"
position: sticky;
top: 30px;
left: 30px;
Flexbox layout (display: flex
)¶
- Layout child elements as rows or columns.
- Properties for configuring spacing, size, alignment, order and direction of child elements.
- Specifically recommended for responsive design, i.e. design that renders well on screens of many different sizes.
Main Axis and Cross Axis
row
or row-reverse
, your main axis will run along the row in the inline direction.
column
or column-reverse
and your main axis will run in the block direction, from the top of the page to the bottom.
flex-direction
(main axis) is set to row
or row-reverse
the cross axis runs down the columns.
column
or column-reverse
then the cross axis runs along the rows.
Flexbox layout¶
- Multiple properties are used together in order to use Flexbox layout
- Some properties are set on the container (also called parent or flex container)
- Some properties are set on the elements in the container (also caled children or flex items)
Some parent container properties¶
display: flex
flex-direction: row
|row-reverse
|column
|column-reverse
flex-wrap: nowrap
|wrap
|wrap-reverse
- (
flex-flow: <flex-direction> <flex-wrap>
) justify-content: flex-start
|flex-end
|center
|space-between
align-items: stretch
|flex-start
|flex-end
|center
|baseline
Properties set on children¶
order: <integer>
flex-grow: <positive number>
flex-shrink: <positive number>
flex-basis: <width/height>
align-self: auto
|flex-start
|flex-end
|center
|baseline
|stretch
flex
(see reference documentation)- Important: Flexbox will override the size property of its children!
Parent properties¶
flex-direction
- Sets the direction of the main axis of the container
row
row-reverse
column
column-reverse
- https://developer.mozilla.org/en-US/docs/Web/CSS/flexdirection
flex-wrap
- Set whether the flex items should be placed on a single row/column or multiple rows/columns
nowrap
wrap
wrap-reverse
- https://developer.mozilla.org/en-US/docs/Web/CSS/flexwrap
Box alignment
Alignment of flexbox items
Main Axis and Cross Axis¶
justify-content
- Control alignment of all flex items on the main axis
start
center
flex-start
flex-end
stretch
space-between
- ... lots more, see reference documentation
- https://developer.mozilla.org/en-US/docs/Web/CSS/justifycontent
align-items
- Control alignment of all flex items on the cross axis
stretch
center
flex-start
flex-end
- ... lots more see reference documentation
- https://developer.mozilla.org/en-US/docs/Web/CSS/align-items
Child properties¶
order
- Set the order (group) of a flex item in the row or column specified by the
flex-direction
of the parent. - By default all items have
order: 0
unless otherwise specified.order: <integer>;
order: -1;
order: 1;
order: 2;
- https://developer.mozilla.org/en-US/docs/Web/CSS/order
flex-grow
- Set how much of the available space will be given to a flex item.
flex-grow: <positive number>;
flex-grow: 1;
flex-grow: 0.6;
- https://developer.mozilla.org/en-US/docs/Web/CSS/flex-grow
flex-shrink
¶
- Set how much a flex-item should shrink if the available space is too small.
- A higher number means more shrinking is allowed.
flex-shrink: <positive number>;
flex-shrink: 0;
flex-shrink: 0.5;
flex-shrink: 1;
flex-shrink: 2;
- https://developer.mozilla.org/en-US/docs/Web/CSS/flex-shrink
flex-basis
¶
- Set the initial width/height of a flex item (depending on the flex-direction).
flex-basis: <width/height>
flex-basis: auto;
flex-basis:
flex-basis: 200px;
- https://developer.mozilla.org/en-US/docs/Web/CSS/flex-basis
align-self
- Set alignment of a single flex item along the cross axis.
- Works like
align-items
but only affects a single item. - https://developer.mozilla.org/en-US/docs/Web/CSS/align-self
justify-self
¶
- Set the alignment of a single flex item along the main axis.
- https://developer.mozilla.org/en-US/docs/Web/CSS/justify-self
Responsive Design¶
Responsive Design¶
- Respond to the display used to render a view, e.g. a HTML document
- high resolution desktop
- tablet
- smartphone
- etc.
Responsive Design¶
- A design can respond by e.g.
- altering sizes of images
- adjusting column widths
- adjusting number of columns used
- placement of navigation
- etc.
- Originally Responsive Web Design (RWD)
Very quick RWD how-to¶
- Set device viewport
- i.e. ask the browser how many pixels (DIPs, Device-Independant-Pixels) wide its display is
<meta name="viewport" content="width=device-width,initial-scale=1">
- Either use media-queries when linking to apply the linked stylesheet only when the media condition is true...
<link rel="stylesheet" media="screen and (min-width:500px)" href="small.css">
- ... or embed media-queries directly in the CSS with
@media
:
@media screen and (min-width: 500px) {
/* your small CSS here */
}
Very quick RWD how-to
- Decide break points, i.e. at which points do layout changes occur.
- Note:
min-width
/max-width
is width of browser window,min-device-width
/max-device-width
is width of screen on device.
Mobile-First Approach¶
- Still responsive, only refers to the order you do things.
- Design and implement for the smallest screen type first, then design and implement extensions of and additions to that design for sequentially larger screens, e.g.
- Mobile → Tablet → Laptop → Desktop.
- Where would you put design for TV screens in that ordering? Why?
- Why mobile-first design?
- Easier to extend an initial design for a small screen to designs for larger screens than the other way around.
- Ensures that the most important elements fit on a small screen without a fundamental re-design.
- Why mobile-first implementation?
- Smaller devices are generally less powerful than larger devices.
- Only load extra CSS for larger screens on more powerful devices.
Some resources¶
- Responsive Web Design – What It Is And How To Use It
- Responsive Web Design Basics
- Responsive design
Typography¶
Typeface, or in CSS, font-family
¶
- Typeface: A particular style of lettering, often mistakenly called a font, and consisting of a canonical letterform for each letter.
- In CSS, the typeface is referred to as the
font-family
.
p {
font-family: "Comic Sans";
}
The font stack¶
- The font stack refers to the series of comma separated typefaces supplied to
font-family
by descending order of preference. - When a browser cannot display the first typeface, the second one is used as fall-back, and so on.
- It is customary to end the stack with one of a number of generic names that the browser will allways be able to resolve.
- The most common being
serif
,sans-serif
, andmonospace
. - Serif typefaces are typefaces that use serifs, i.e. slight projections added to the ends of strokes, like Times New Roman. Conversely, sans-serif refers to typefaces lacking serifs, like Arial.
- Monospace typefaces are typefaces where every symbol has the same width, like Courier New.
- The most common being
p {
font-family: Helvetica, Arial, sans-serif;
}
font-weight
¶
- The thickness of the strokes making up indvidual letters refers to the weight of the font. This is set by
font-weight
as a number between1
and1000
or a keyword with the keywordnormal
equalling400
andbold
equalling700
. - The thickness can also be set relative to the parent element using the keywords
lighter
andbolder
.
p {
font-family: "Comic Sans";
font-weight: 300;
}
font-style
¶
- A typeface can be be displayed in roman (
normal
) form, i.e. standard upright form, or in italicized (italic
) or oblique (oblique
) form. This is set byfont-style
. - Historically, the italic form was a special cursive version of the typeface with different letterforms, while the oblique form was simply a slanted version of the roman letterforms. Today, italics are often identical to obliques but some fonts still have separate italic and oblique versions.
- It is also possible, using some fonts, to set the oblique angle, i.e. how many degrees to slant the letterform.
p {
font-family: "Comic Sans";
font-style: italic;
}
font-size
¶
- We can also set the size of a font using
font-size
. - The size can be set to an absolute size using keywords
xx-small
-xxx-large
or absolute length units (e.g.pt
,cm
). - The size can also be set relative to the
font-size
of the parent element's (e.g. using the keywordssmaller
orlarger
or the unitsem
,ex
or%
) or the root element (using the unitrem
).
p {
font-family: "Comic Sans";
font-size: 42pt;
}