0% found this document useful (0 votes)
0 views94 pages

CSS Notes

CSS, or Cascading Style Sheets, is a standard language used to style HTML documents and can also be applied to other structured formats like XML. It allows for the separation of content (HTML) from presentation (CSS) through various methods of application: inline, internal, and external styles. CSS syntax consists of selectors, properties, and values, enabling developers to customize the appearance of web elements effectively.

Uploaded by

sahil mehta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views94 pages

CSS Notes

CSS, or Cascading Style Sheets, is a standard language used to style HTML documents and can also be applied to other structured formats like XML. It allows for the separation of content (HTML) from presentation (CSS) through various methods of application: inline, internal, and external styles. CSS syntax consists of selectors, properties, and values, enabling developers to customize the appearance of web elements effectively.

Uploaded by

sahil mehta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 94

 CSS, or Cascading Styles Sheets, is a way to style and present HTML.

 Whereas the HTML is the meaning or content,

 The style sheet is the presentation of that document.

 CSS stands for Cascading Style Sheets.

 CSS is the standard language for defining styles on web pages.


Although CSS is more widely known for its application in HTML
documents, it can be used for defining styles for any structured
document format (such as XML for example).

 Styles are set using CSS properties. For example, you can set font
properties (size, colors, style etc), background images, border styles,
and much more.

 There are three ways to apply CSS to HTML:

1. Inline
2. Internal
3. External

Inline

Inline styles are placed straight into the HTML tags using the style attribute.

They look something like this:

<p style="color: red">text </p>

This will make that specific paragraph red.

Page | 1
But, if you remember, the best-practice approach is that the HTML should
be a stand-alone, presentation free document, and so in-line styles should
be avoided wherever possible.

Internal

 Embedded, or internal, styles are used for the WHOLE PAGE.

 Inside the head element, the style tags surround all of the styles for
the page.

<!DOCTYPE html>
<html>
<head>
<title>CSS Example</title>
<style>

p{
color: red;
}

a{
color: blue;
}

</style>

 This will make all of the paragraphs in the page red and all of the
links blue.

 Although preferable to soiling our HTML with inline presentation, it is


similarly usually preferable to keep the HTML and the CSS files
separate
External
Page | 2
 External styles are used for the whole, multiple-page website.

 There is a separate CSS file, which will simply look something like:

p{
color: red;
}

a{
color: blue;
}

 If this file is saved as “style.css” in the same directory as your HTML


page then it can be linked to in the HTML like this:

<!DOCTYPE html>

<html>
<head>
<title>CSS Example</title>

<link rel="stylesheet" href="style.css">

HTML vs CSS
Page | 3
It's not really "HTML vs CSS".

In fact HTML and CSS are the best of friends! CSS is a supplementary
extension to HTML. Here's what each does:

HTML

 The purpose of HTML is to provide document structure and


meaning.

 This is particularly true with the introduction of HTML5.

 You use HTML to specify what elements go on the page (eg,


headings, paragraphs, tables, images, etc).

 Each of these elements (as well as their attributes and attribute


values) has a certain meaning.

CSS

 You use CSS to specify how those HTML elements look

 So, you can write an HTML document without being concerned with
its presentation, and then use CSS to specify how it will be presented
within any given context.

 Not only this, but you can change the CSS without having to change
the HTML. In other words, you can "plug" a style sheet into an HTML
document and the HTML document will immediately take on the
styles of that style sheet.

Page | 4
Example
<!DOCTYPE html>
<html>

<head>
<title>Example</title>
</head>
<body>

<main>

<h1>HTML Page</h1>
<p>This is a basic web page.</p>

</main>

</body>

</html>

Page | 5
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<style>
main {
width: 200px;
height: 200px;
padding: 10px;
background: beige;
}

h1 {
font-family: fantasy, cursive, serif;
color: olivedrab;
border-bottom: 1px dotted darkgreen;
}

p{
font-family: sans-serif;
color: orange;
}

</style>
</head>

<body>

<main>
<h1>HTML Page</h1>
<p>This is a basic web page.</p>

</main>

</body>
</html>

Page | 6
CSS Syntax — How to Code CSS

The CSS syntax consists of a set of rules.

These rules have 3 parts:

1. Selector
2. Property
3. Value

You don't need to remember this in order to code CSS.

Once you start coding CSS, you'll do so without thinking "this is a selector"
or "that is a property".

Syntax

 Selector {property: value}

 The selector represents the HTML element that you want to style.
For example:

h1 { color: blue }

 This code tells the browser to render all occurrences of the HTML <h1>
element in blue.

Page | 7
Grouping Selectors

 You can apply a style to many selectors if you like. Just separate the
selectors with a comma.

h1, h2, h3, h4, h5, h6 { color: blue }

Applying Multiple Properties

 To apply more than one property separate each declaration with a


semi-colon.

h1 { color:blue; font-family: arial, helvetica, "sans serif" }

Readability

 You can make your CSS code more readable by spreading your style
declarations across multiple lines.

 You can also indent your code if you like.

 This doesn't affect how your code is rendered - it just makes it easier
for you to read.

h1 {
color: blue;
font-family: arial, helvetica, "sans serif";
font-size: 150%;
}

Page | 8
CSS Class Selectors

 Selectors are the things we apply a style against.

 In our examples, our selectors were all HTML elements.

 For example, we decided to make the <h1> element blue.

 Now, that works well if you want all headings to be blue.

 But what if you only want some of your headings to be blue?

 Perhaps you want the color of your headings to reflect the section of
the site that you're in.

 Sounds like you need to use classes!

 In CSS, classes allow you to apply a style to a given class of an


element.

 To do this, you link the element to the style by declaring a style for
the class, then assigning that class to the element.

Page | 9
CSS Class Syntax

 You declare a CSS class by using a dot (.) followed by the class
name.

 You make up the class name yourself.

 After the class name you simply enter the properties/values that you
want to assign to your class.

 If you want to use the same class name for multiple elements, but
each with a different style, you can prefix the dot with the HTML
element name.

p.large {font-size: 2em ;}

 If you want to use the same class name for multiple elements, but
each with a different style, you can prefix the dot with the HTML
element name.

<!DOCTYPE html>
<title>Example</title>
<style>
div.css-section {
border:1px dotted red;
padding: 20px;
}
p.css-section {
color:green;
}
</style>
<div class="css-section">CSS Class</div>
<p class="css-section">CSS classes can be very useful</p>

Page | 10
You can also select elements (or classes) that's nested within another
element or class.

For example, div.css-section p will select all <p> elements that are nested
within a <div> element that uses the .css-section class.

One major benefit of doing this is that you don't need to apply a class to
every instance of an element when it's nested within another element that
uses a class.

Here's an example:

Page | 11
<!DOCTYPE html>

<title>Example</title>

<style>
div.css-section {
border:1px dotted red;
padding: 20px;
}

div.css-section p {
color:green;
}

</style>

<div class="css-section">CSS Class

<p>CSS classes can be very useful</p>

</div>

So here div.CSS-section p will take styles of Border of red and Padding of


div.CSS-section class

Page | 12
CSS ID Selectors

 You can assign a unique identifier to an HTML element, then style


that element by referencing its unique identifier.

 This allows you to define a style that can only be used by the element
you assign the ID to.

 Any HTML element can have the id attribute applied to it.

 The value of this attribute is the element's unique identifier.

 For example, <h1 id="mainHeading"> gives that element a unique


identifier of mainHeading.

 We can reference that ID from within our CSS code.

CSS ID Syntax

The syntax for declaring a CSS ID is the same as for classes, except that
instead of using a dot, you use a hash (#).

#id-name { property:value; }

Again, similar to classes, if you want to use the same id name for multiple
elements, but each with a different style, you can prefix the hash with the
HTML element name

Page | 13
<!DOCTYPE html>
<title>Example</title>
<style>

div#css-section {
border:1px dotted red;
padding: 20px;
}

</style>

<div id="css-section">

This lucky div has ID...

</div>

<div>

This poor div has no ID...

</div>

 Here the First div is applied with ID so it will take div#css-section and
hence applied Red dotted border with Padding

 Second div is applied without ID so it just showed simple text with div
only

Page | 14
When to use classes

 You should use classes when your style needs to be applied multiple
times on the same page.

 For example, you might have many <h1> elements that need the
same style applied.

When to use IDs

 You should use IDs if only one element on the page should have the
style applied, and/or you need a unique identifier for that element.

 For example, you might assign an ID to a <nav> tag which contains


your left menu.

 The styles for this ID could contain the position, background-color,


float properties, size etc.

 You probably wouldn't want any other element on the page to use
this particular style.

 Another useful thing about IDs is that you can use the Document
Object Model (DOM) to refer to them.

 This enables you to use JavaScript/DHTML techniques to build a


much more interactive web site.

Page | 15
CSS Font Properties

 Here, we look at the various font properties.

 These are the properties in the font namespace — those that include
the word font at the start of their name.

 CSS font properties enable you to change the look of your text.

 For example, you can assign a font family, apply bold or italic
formatting, change the size and more.

CSS Font Family

 The font-family property accepts a list of different font families.

 This is because, not all users will have the same fonts installed on
their computer.

 Therefore, as a designer/developer, you can provide a list of fonts,


starting with your first choice, and ending with your last choice.

 So, if the user doesn't have your first choice font, the second choice
will be used for that user.

 If they don't have the second choice, the third choice will be used,
and so on.

 It's good practice to make your last choice a generic font family such
as serif or sans-serif (depending on whether you want a font with
serifs or not).

Page | 16
 This way, if none of the other choices are on the user's computer,
their computer will choose a font that is on their computer, based on
the generic family that you provide.

<!DOCTYPE html>

<title>Example</title>
<style>

p{
font-family: Georgia, Garamond, serif;
}

</style>

<p>This text is rendered in either georgia, garamond, or the default serif


font (depending on which font the user's system has).</p>

Page | 17
CSS Font Size

Enables you to set the size of the text.

For info on the possible values, see the font-size page.

<!DOCTYPE html>

<title>Example</title>

<style>

p{
font-size: 30px;
}

</style>

<p>This text is using a font size of 30 pixels.</p>

Page | 18
CSS Font Style

The font-style property is used for specifying italic text.

<!DOCTYPE html>

<title>Example</title>

<style>
p{
font-style: italic;
}
</style>

<p>This text is in italics.</p>

Page | 19
CSS Text Properties

 Apart from the various CSS font properties, there are other properties
that can assist in styling your text.

 For example, you can change the color of text, align text, add decoration
properties and more.

 In CSS, text can be styled using the properties listed below.

 Using this list, you can learn how to use each css text property and what
it looks like in a browser.

<!DOCTYPE html>
<title>Example</title>
<style>

p{
color: olive;
}

</style>

<p>This CSS text color is olive</p>

Page | 20
CSS Text Align

For more information, see the text-align property.

<!DOCTYPE html>

<title>Example</title>

<style>

p{
text-align: right;
}

</style>

<p>This CSS text is aligned right</p>

CSS Text Transform


Page | 21
<!DOCTYPE html>

<title>Example</title>

<style>
.uppercase {
text-transform: uppercase;
}

.lowercase {
text-transform: lowercase;
}

.capitalize {
text-transform: capitalize;
}
</style>

<p class="uppercase">This text has been transformed to uppercase</p>

<p class="lowercase">THIS TEXT HAS BEEN TRANSFORMED TO


LOWERCASE</p>

<p class="capitalize">this text has been capitalized.</p>

CSS Text Decoration

Page | 22
For more information, see the text-decoration property.

<!DOCTYPE html>
<title>Example</title>
<style>
.overline {
text-decoration: overline;
}

.line-through {
text-decoration: line-through;
}

.underline {
text-decoration: underline;
}

a:link {
text-decoration: none;
}

</style>

<p class="overline">This text has a line over the top</p>


<p class="line-through">This text has a line through the middle</p>
<p class="underline">This text has a line underneath</p>
<a href="/css/" target="_blank">This hyperlink has no underline</a>

Page | 23
CSS Height and Width Properties

 height and width Properties

 Applies to all HTML elements except non-replaced inline elements


like table columns and column groups.

 You can use a fixed height (i.e. pixels) or a percentage height. For
more info, see height and width.

<!DOCTYPE html>
<title>Example</title>
<style>

div {
height: 150px;
width: 75px;
background-color: gold;
}

</style>

<div>

This div has height and width applied.

</div>

Page | 24
max-height and max-width Properties

 The CSS max-height property is used to constrain the height of an


element. The element can render at any size up to the max-height,
depending on its contents.

<!DOCTYPE html>
<title>Example</title>
<style>

div {
max-height: 150px;
max-width: 75px;
background-color: gold;
}

</style>

<div>

This div has 'max-height' and 'max-width' applied.

</div>

Page | 25
min-height and min-width Properties

 Enables you to constrain the height and/or width of an element to a


minimum value.

 The CSS min-height property is used to constrain the height of an


element.

 The element can render at any size up to the min-height, depending on


its contents.

<!doctype html>

<title>Example</title>

<style>

button {
background: greenyellow;
min-width: 100px;
min-height: 50px;
}

</style>

<button>

min-height

</button>

Page | 26
CSS Background Code

CSS Background Color


To set the background color of an element, use the background-color property.

<!DOCTYPE html>

<title>Example</title>

<style>

div {
padding: 20px;
background-color: yellow;
}

</style>

<div>

This 'div' has a background color applied.

</div>

CSS Background Image


Page | 27
 To add a background image to an element, use the background-image
property

 By default, if a background image is smaller than its containing box, it


will repeat both horizontally and vertically until it fills up the box.

 You can change this behavior with the background-repeat property.

<!DOCTYPE html>

<title>Example</title>

<style>
div {
padding: 70px;
background-image: url("/pix/samples/bg2.png");
}

</style>

<div>
This 'div' has a background image applied.
</div>

Page | 28
CSS background-repeat

The CSS background-repeat property is used to specify if a background


image repeats (tiles) or not, and how it should repeat.

By default, background images repeat horizontally and vertically across the


width and height of the background painting area.

However, you can change this behavior with the background-repeat


property.

You can stop the image from repeating altogether (so that it only appears
once), or you can specify exactly how it repeats, especially when also using
the background-position and/or the background-size property.

The background-repeat property can also be used with multiple


background images (i.e. if you specify multiple values for the background-
image property).

Page | 29
<!doctype html>
<title>Example</title>
<style>

.imageRepeatBox {
height: 150px;
border: 1px solid black;
padding: 10px;
background-image: url("/pix/samples/bg1.gif");
background-repeat: no-repeat;
background-position: 90% 30%;
}

</style>

<div class="imageRepeatBox">

<p>This div element has a background-image with background-


repeat set to no-repeat.</p>

<p>You can also try using repeat-x or repeat-y.</p>

Page | 30
CSS background-attachment

The CSS background-attachment property specifies whether a background


image should be fixed or scroll with the containing block.

Page | 31
CSS Border Properties
CSS allows you to set styles for the border of any HTML element.

It also provides you with a way of setting border styles for one or more
sides of an element.

Setting Borders on all Sides

 To set border styles for all sides of an element, you use the border-
width, border-style, and border-color properties.

 You can also use the border property to set all properties at once.

border-width, border-style, and border-color

<!DOCTYPE html>
<title>Example</title>
<style>

div {
padding: 20px;
border-width: 1px;
border-style: solid;
border-color: orange;
}

</style>
<div>
This 'div' has border styles applied using the border-width, border-style,
and border-color properties.
</div>

Page | 32
The border Property

The border property is shorthand for setting border-width, border-style, and


border-color.

<!DOCTYPE html>

<title>Example</title>

<style>

div {
padding: 20px;
border: 1px solid orange;
}

</style>

<div>

This 'div' has border styles applied using the 'border' property.

</div>

Page | 33
Border Styles

Borders can have the following styles.

<!DOCTYPE html>
<title>Example</title>
<style>
div {
padding: 5px;
margin: 10px;
text-align: center;
border-color: orange;
border-width: 4px;
}

.solid {
border-style: solid;
}

.dotted {
border-style: dotted;
}

.dashed {
border-style: dashed;
}

.double {
border-style: double;
}

.groove {
border-style: groove;
}

.ridge {
border-style: ridge;
}

.inset {

Page | 34
border-style: inset;
}

.outset {
border-style: outset;
}

.hidden {
border-style: hidden;
}

</style>

<div class="solid">This 'div' has a border style of 'solid'.</div>


<div class="dotted">This 'div' has a border style of 'dotted'.</div>
<div class="dashed">This 'div' has a border style of 'dashed'.</div>
<div class="double">This 'div' has a border style of 'double'.</div>
<div class="groove">This 'div' has a border style of 'groove'.</div>
<div class="ridge">This 'div' has a border style of 'ridge'.</div>
<div class="inset">This 'div' has a border style of 'inset'.</div>
<div class="outset">This 'div' has a border style of 'outset'.</div>
<div class="hidden">This 'div' has a border style of 'hidden'.</div>

Border Radius

Page | 35
You can give your borders rounded corners by using the border-radius
property.

Page | 36
CSS Margin Properties

Margins define the space around the element. CSS margins are specified
in a similar way to borders - they can be set individually for each side, or all
sides at once.

<!DOCTYPE html>
<title>Example</title>
<style>

div {
border: 1px solid orange;
}

div > p {
background: gold;
margin: 20px;
}

</style>

<div>

<p>
This text has a margin of 20 pixels on all four sides. It is nested within a div with a
border to make it easier to see the effect of the margin.
</p>

</div>

Page | 37
Shorthand Property

This method uses a shorthand property for setting margin-top, margin-right,


margin-bottom, and margin-left in the one place.

This method is quicker. It also uses less code than the previous method.

Actually, it's the same property that we used in our first example (i.e. the
margin property). The only difference is that we apply multiple values
against it.

<!DOCTYPE html>
<title>Example</title>
<style>

div {
border: 10px solid lightblue;
}

div > p {
border: 1px dotted orange;
margin: 20px 50px 10px 30px;
}

</style>

<div>
<p>

This text has a different sized margin for each side. It is nested
within a 'div' with a border to make it easier to see the effect of the
margin.

</p>
</div>

Page | 38
Variations

You don't need to provide different values for all four sides.

You can provide one, two, three, or four values. Here's how it works:

If there is only one value, it applies to all sides.

If there are two values, the top and bottom margins are set to the first value
and the right and left margins are set to the second.

If there are three values, the top is set to the first value, the left and right
are set to the second, and the bottom is set to the third.

If there are four values, they apply to the top, right, bottom, and left,
respectively.

In other words:

margin:10px;
 All four sides have a margin of 10 pixels.

margin:10px 20px;
 Top and bottom have a margin of 10 pixels.
 Right and left have a margin of 20 pixels.

margin:10px 20px 30px;


 Top is 10px
 Left and right are 20px
 Bottom is 30px

margin:10px 20px 30px 40px;


 Top is 10px
 Right is 20px
 Bottom is 30px
 Left is 40px

Page | 39
CSS Padding Properties

Padding defines the space between the element's border and its content.

CSS padding is specified just like margins — it can be set individually for
each side, or all sides at once.

Set the Same Padding on all Sides

This example uses the padding shorthand property to set the same
padding on all sides of an element.

<!DOCTYPE html>
<title>Example</title>
<style>

div {
background: gold;
padding: 20px;
}

div > p {
background: white;
}

</style>

<div>
<p>
Padding of 20 pixels on all four sides.
</p>
</div>

Page | 40
Setting Padding for Each Side

If you don't want the same padding settings to be applied to all four sides,
or if you want each side to have different padding, you can use the
following properties:

 padding-top
 padding-right
 padding-bottom
 padding-left

<!DOCTYPE html>
<title>Example</title>
<style>

div {
background: gold;
padding-top: 5px;
padding-right: 60px;
padding-bottom: 15px;
padding-left: 30px;
}

div > p {
background: white;
}

</style>

<div>
<p>
Different padding on each side.
</p>
</div>

Page | 41
Shorthand Property

The padding property is shorthand for padding-top, padding-right, padding-


bottom, and padding-left.

<!DOCTYPE html>
<title>Example</title>

<style>

div {
background: gold;
margin: 20px;
padding: 5px 60px 15px 30px;
}

div > p {
background: white;
}

</style>

<div>
<p>
Different padding on each side.
</p>
</div>

Page | 42
Variations

 Again, as with margin, you don't need to provide different values for
all four sides.

 You can provide one, two, three, or four values. Here's how it works:

 If there is only one value, it applies to all sides.

 If there are two values, the top and bottom paddings are set to the
first value and the right and left paddings are set to the second.

 If there are three values, the top is set to the first value, the left and
right are set to the second, and the bottom is set to the third.

 If there are four values, they apply to the top, right, bottom, and left,
respectively.

 In other words

 Same as Borders explained earlier

Page | 43
How to Style Lists with CSS

HTML lists can have a number of different styles applied using CSS. Here
are some of the commonly used ones.

List Style Type


Determines what the bullet looks like. For info on the possible values see
the list-style-type page.

<!DOCTYPE html>

<title>Example</title>

<style>

ul {
font-size: 1.5em;
list-style-type: circle;
}

</style>

<ul>

<li>List item one</li>


<li>List item two</li>
<li>List item three</li>

</ul>

List Style Image


Page | 44
For more information on using images for your bullet points, see list-style-
image.

<!DOCTYPE html>

<title>Example</title>

<style>

ul {
font-size: 22px;
list-style-image: url("/pix/samples/bullet1.png");
}

</style>

<ul>

<li>List item one</li>


<li>List item two</li>
<li>List item three</li>

</ul>

List Style Position

Page | 45
Determines whether the bullet is located inside the list's containing box or
outside.

<!DOCTYPE html>

<title>Example</title>

<style>

ul {
font-size: 1.5em;
}

.inside {
list-style-position: inside;
}

.outside {
list-style-position: outside;
}

</style>

<ul class="inside">

<li>List item one</li>


<li>List item two</li>
<li>List item three</li>

</ul>

<ul class="outside">

<li>List item one</li>


<li>List item two</li>
<li>List item three</li>
</ul>

Page | 46
Page | 47
List Style

The list-style property is shorthand for setting the list properties.

<!DOCTYPE html>

<title>Example</title>

<style>

ul {
font-size: 1.5em;
list-style: square inside;
}

</style>

<ul>

<li>List item one</li>


<li>List item two</li>
<li>List item three</li>

</ul>

Page | 48
CSS Float

 The CSS float property enables you to determine where to position


an element relative to the other elements on the page.

 When you use the float property, other elements will simply wrap
around the element you applied the float to.

Float Left Example

 In this example, we set a <div> element to float: left, which results in


the rest of the content wrapping around it.

 Note that I apply a margin to the right and bottom of the box, so that
the rest of the content doesn't run right up against the box.

Page | 49
<!DOCTYPE html>

<title>Example</title>

<style>

.float-left {
float: left;
padding: 20px;
margin: 0 10px 10px 0;
background: gold;
}

</style>

<div class="float-left">
Float left
</div>

<p>This text rearranges itself to flow around the element that is


floated left. </p>

<p>I added a margin to the right and bottom of the floated box so
that this text doesn't run right up against it. Play around with
the property values to see how it changes the layout.</p>

Page | 50
Aligning Boxes Side by Side

Here we use float: left to align <div> elements side by side.

Normally these elements would stack up on top of each other, but by using
float: left, we can get them to display next to each other.

<!DOCTYPE html>

<title>Example</title>

<style>

div {
float: left;
padding: 20px;
}

.gold {
background: gold;
}

.limegreen {
background: limegreen;
}

.orange {
background: orange;
}

</style>

Page | 51
<div class="gold">
Gold
</div>

<div class="limegreen">
Limegreen
</div>

<div class="orange">
Orange
</div>

Page | 52
CSS Flexbox and Grid

 CSS flexbox and grid can be used for creating website layouts and
positioning items on a web page. Here's an overview.

 CSS flexbox and grid are two different layout models optimized for
user interface design.

 Flexbox (also known as flexible box layout) deals with one-


dimensional layouts, where you can lay out and align elements
horizontally or vertically.

 Grid (also known as grid layout) goes a step further and allows you to
build two-dimensional layouts, where you can lay out and align
elements horizontally and vertically.

Flexbox

 Flexbox includes a number of properties that allow you to define a


flexible box, as well as the behavior of the items inside it.

 First, you declare the flex container by applying display: flex or


display: inline-flex to it.

 This establishes a new flex formatting context for its contents.

 Once you have a flex container, you can then apply the various flex
properties to its children.

 The flex property is shorthand for the main flex properties, and it goes
like this:
Page | 53
<!DOCTYPE html>

<title>Example</title>

<style>

.outer-container {
font: 16px sans-serif;
background: gold;
color: white;
height: 200px;
display: flex;
}

.box {
padding: 10px;
flex: 1 0 auto;
}

.larger {
background: yellowgreen;
flex: 3 0 auto;
}

</style>

<div class="outer-container">

<div class="box">Box</div>
<div class="box larger">Larger Box</div>
<div class="box">Box</div>
<div class="box larger">Larger Box</div>

</div>

Page | 54
 Here, we specify that the normal box "grow factor" is 1 and the larger
box is 3.

 The grow factor specifies how much the flex item grows relative to the
rest of the flex items in the flex container.

Page | 55
 Flexbox - Introduction
 Flexbox - Create a Flexbox
 Flexbox - Create a Website Layout
 Flexbox - Nested Flex Containers
 Flexbox - Create a Responsive Layout
 Flexbox - Align Form Elements
 Flexbox - Create a Media Object
 Flexbox - Alignment
 Flexbox - Direction

The CSS Flexible Box Layout Module was developed by the CSS Working
Group to provide a box model that can be used for laying out more complex
applications and webpages than the previous models were designed for.

Page | 56
Flexbox Introduction

 Flexbox is a layout model designed to help web authors create


advanced website layouts that are difficult to achieve using other
layout models.

 CSS flexbox (also referred to as flexible box) provides web authors


with control over how elements are positioned, aligned, and sized
within their container.

 It allows you to do things like, specify how elements are aligned


vertically and horizontally, change their order of appearance, change
the direction in which all elements are laid out, and more.

 Prior to flexbox, common website layouts were often difficult to


achieve, due to limitations in the existing layout models.

 The block layout model was designed for document layout.

 The inline model was designed for text.

 The table layout model was designed for laying out 2D data in a
tabular format.

 Positioned layout allowed very explicit positioning of an element


without regard to other elements in the document.

Page | 57
 Due to the limitations of these layout models, website layouts were
often achieved using a combination of floated elements, positioned
elements, and maybe even table layout.

 Getting a website to look right across various screen sizes was


usually a headache.

 The only way to get a website to look right was to incorporate a


bunch of hacks — that often seemed counter-intuitive — in both the
CSS and the HTML code.

 This goes against the whole "separation of presentation and content"


approach that any decent web developer strives for.

 The CSS Flexible Box Layout Module was developed by the CSS
Working Group to provide a box model that could overcome those
issues.

Page | 58
CSS display

 The CSS display property is used to specify whether an element


should be displayed and if so, how it will be displayed.

 The display property specifies an element's display type.

 Display type refers to how an element generates boxes.

 There are two basic display types:

Inner display type

Defines (if it's a non-replaced element) the kind of formatting context


it generates, which dictates how its descendant boxes are laid out.

Outer display type

Dictates how the box participates in its parent formatting context.

Create a Flexible Box with Flexbox

We'll create one flex container and put three flex items inside it. We'll also
see how we can affect their size by adding more content, and playing
around with some property values.

Page | 59
<!doctype html>

<title>Example</title>

<style>
.container {
display: flex;
}

.red {
background: orangered;
flex-grow: 1;
}

.green {
background: yellowgreen;
}

.blue {
background: steelblue;
}

.container > div {


font-size: 5vw;
padding: .5em;
color: white;
}
</style>

<div class="container">

<div class="red">1</div>
<div class="green">2</div>
<div class="blue">3</div>

</div>

Page | 60
 We use display: flex to declare the outer element as a flex container.

 That's all we need in order to start using flexbox.

 Now all of that flex container's in-flow children automatically become flex
items and are therefore laid out using the flex layout model.

 But you'll notice that the red flex item is wider than the other two.

 This is because we applied flex-grow: 1 to that item.

 The flex-grow property sets the flex item's grow factor, which determines
how much the flex item will grow relative to the other flex items (after
any positive free space is distributed).

 The initial value is zero, so the other two items have a grow factor of
zero (because we haven't used the flex-grow property on those items).

 This causes the red flex item to grow as much as needed to take up the
available space.

 The other two items oblige by shrinking until they just fit their contents
and no more.

Page | 61
Adding Content

You might be wondering why we didn't just set the width of the red item by
using the width property?

Yes, we could've done that. But if we had, I wouldn't have been able to
show you this next bit...

<!doctype html>
<title>Example</title>
<style>
.container {
display: flex;
}

.red {
background: orangered;
flex-grow: 1;
}

.green {
background: yellowgreen;
}

.blue {
background: steelblue;
}

.container > div {


font-size: 5vw;
padding: .5em;
color: white;
}
</style>

Page | 62
<div class="container">

<div class="red">1</div>
<div class="green">2</div>
<div class="blue">3
<p>Flexbox items can grow and shrink as required to fit their
contents.</p> </div>

</div>

 All I did was add some content to the blue item, and it grew as required
in order to fit the new content.

 In fact, there was so much content, that the red item completely shrunk
to fit its own contents and no more.

 So this is what I meant when I said the grow factor determines how
much the item will grow after any positive free space is distributed.

 By adding so much content to the blue item, we effectively removed the


available free space, and the red item had nowhere to grow.

 The height of the blue flex item also grew to accommodate the new
content. And just as importantly, the other two items also increased their
height to match.

Page | 63
 With flexbox all this happens by default, so this saves us from having to
tweak heights and widths to try to get all our boxes looking even.

Changing the Width

So now that I've showed you that you don't need to set the width on your
flex items, let's see what happens we do set the width.

<!doctype html>

<title>Example</title>

<style>
.container {
display: flex;
}

.red {
background: orangered;
flex-grow: 1;
}

.green {
background: yellowgreen;
}

.blue {
background: steelblue;
width: 40vw;
}

.container > div {


font-size: 5vw;
padding: .5em;
color: white;
}
</style>

<div class="container">

<div class="red">1</div>
<div class="green">2</div>
<div class="blue">3
<p>Flexbox items can grow and shrink as required to fit their contents.</p></div>

Page | 64
</div>

 As expected, the blue item becomes as wide as the specified width.

 But because this now reduces the size of the blue item, the red item
grows again — but only as much as required to take up the available
free space.

 So now we're starting to see why it's called flexible box layout.

 Our flex items are nice and flexible — they seem happy to fit in with
whatever's going on around them.

 You can probably imagine how easy it would be to take this a step
further and create a basic template for a website layout. So let's do that
now.

Page | 65
Create a Website Layout with Flexbox

Flexbox is ideal for creating commonly used website layouts such as the three-column, so-called holy
grail layout, where all columns need to remain at full height, regardless of how much (or little) content
resides within them. And where the main content comes before the navbar in the source code, but not
in the presentation.

<!doctype html>

<title>Example</title>
<style>
*{
box-sizing: border-box;
}

body {
margin: 0;
}

#main {
display: flex;
min-height: calc(100vh - 40vh);
}

#main > article {


flex: 1;
}

#main > nav,


#main > aside {
flex: 0 0 20vw;
background: beige;
}

Page | 66
#main > nav {
order: -1;
}

header, footer, article, nav, aside {


padding: 1em;
}

header, footer {
background: yellowgreen;
height: 20vh;
}
</style>

<body>

<header>Header</header>

<div id="main">
<article>Article</article>
<nav>Nav</nav>
<aside>Aside</aside>
</div>

<footer>Footer</footer>

</body>

 Prior to flexbox, this layout was notoriously difficult to achieve without using a hack
of some sort.

 Developers would often have to do things like add extra markup, provide negative
margins, and use other tricks in order to get everything to line up correctly
regardless of the amount of content or the screen size.

Page | 67
 But as the above example shows, flexbox makes it quite trivial. Here's a quick
rundown of the code.

 In the example, we make the #main element the flex container, and leave the header
and footer as block elements. In other words, only the middle bit is flexbox.

Create a Responsive Layout with Flexbox

 You can combine flexbox with media queries to create a layout that responds to
different sized screens.

 Media queries are commonly used in responsive designs in order to display a


different layout to different devices, depending on their screen size.

 The reason for this is that certain layouts will always look too squashed (or even
completely broken) when viewed on narrower screens.

 For example, you can use media queries to display layout 1 to wide screens
(desktops, laptops, etc), layout 2 to medium sized screens (tablets, large
phones), and layout 3 to narrow screens (mobile phones, etc).

 Here, we'll take the layout that we created previously, and add a media query to it
so that it displays differently on smaller devices/viewports.

Page | 68
<!doctype html>
<title>Example</title>
<style>

*{
box-sizing: border-box;
}

body {
display: flex;
min-height: 100vh;
flex-direction: column;
margin: 0;
}

#main {
display: flex;
flex: 1;
}

Page | 69
#main > article {
flex: 1;
}

#main > nav,

#main > aside {


flex: 0 0 20vw;
background: beige;
}

#main > nav {


order: -1;
}
header, footer
{
background: yellowgreen;
height: 20vh;
}

header, footer, article, nav, aside


{
padding: 1em;
}

@media screen and (max-width: 575px)


{
#main {
display: block;
}
}
</style>

<body>

<header>Header</header>

<div id="main">

<article>Article</article>
Page | 70
<nav>Nav</nav>

<aside>Aside</aside>

</div>

<footer>Footer</footer>

</body>

 This example should be displaying all items stacked on top of each other.

 If not, you are probably viewing this on a wide screen.

 In that case, reduce the size of your browser window until you see the layout
collapse down.

 Click the Preview button to view the example on a wider screen (this probably will
not work if you are already viewing this on a mobile device).

 In any case, here's what we added to the code:

Page | 71
@media screen and (max-width: 575px)
{
#main {
display: block;
}
}

 All we did here was change display: flex to display: block.

 We did this on the #main element so that its children are no longer flex items.

 This results in them stacking up on top of each other in source order.

 However, what if we didn't want the items to appear in source order? What if we
want the navbar to appear before the article?

 In that case, we could replace that change with another (just as simple) change.
We could do this:
<!doctype html>

<title>Example</title>

<style>
*{
box-sizing: border-box;
}

body
{
display: flex;
min-height: 100vh;

Page | 72
flex-direction: column;
margin: 0;
}

#main {
display: flex;
flex: 1;
}

#main > article {


flex: 1;
}

#main > nav,

#main > aside {


flex: 0 0 20vw;
background: beige;
}

#main > nav {


order: -1;
}

header, footer
{
background: yellowgreen;
height: 20vh;
}

header, footer, article, nav, aside


{
padding: 1em;
}

@media screen and (max-width: 575px)


Page | 73
{
#main
{
flex-direction: column;
}
}

</style>

<body>

<header>Header</header>

<div id="main">

<article>Article</article>

<nav>Nav</nav>

<aside>Aside</aside>

</div>

<footer>Footer</footer>
</body>

Here is what we did instead:

@media screen and (max-width: 575px)


{
#main
{
flex-direction: column;
}
}

Page | 74
So now, we have the navbar, the article, and then the sidebar.

But you'll notice that the navbar and sidebar are taller than the previous example.

How weird!

Actually, this is happening because of this piece of code:

#main > nav,


#main > aside {
flex: 0 0 20vw;
background: beige;
}

Specifically, the bit that goes flex: 0 0 20vw is setting the flex-basis to 20vw, which is 20
percent of the viewport's width.

We had previously applied this value for the width of the elements, but now that the flex-
direction is column, it uses that value for their height.

If we only want the height to be based on the content, we could change this value to
auto or remove the declaration altogether:

<!doctype html>

Page | 75
<title>Example</title>

<style>
*{
box-sizing: border-box;
}

body {
display: flex;
min-height: 100vh;
flex-direction: column;
margin: 0;
}

#main {
display: flex;
flex: 1;
}

#main > article {


flex: 1;
}

#main > nav,

#main > aside {


background: beige;
}

#main > nav {


order: -1;
}

Page | 76
header, footer {
background: yellowgreen;
height: 20vh;
}

header, footer, article, nav, aside


{
padding: 1em;
}

@media screen and (max-width: 575px)


{
#main
{
flex-direction: column;
}
}

</style>

<body>
<header>Header</header>
<div id="main">
<article>Article</article>
<nav>Nav</nav>
<aside>Aside</aside>
</div>
<footer>Footer</footer>
</body>

Page | 77
Mobile First

 We could switch the code around so that our layout becomes a "mobile first"
layout.

 Mobile first is a term for layouts those are created primarily for mobile devices,
but include a media query that changes the layout on larger devices.

 That is the opposite of what we did above, where our default layout was for large
devices, and we added the media query for smaller devices.

 Therefore, we can take the above example and modify it like this:

Page | 78
<!doctype html>

<title>Example</title>

<style>

*{
box-sizing: border-box;
}

body
{
display: flex;
min-height: 100vh;
flex-direction: column;
margin: 0;
}

#main
{
display: flex;
flex: 1;
flex-direction: column;
}

#main > article {


flex: 1;
}

#main > nav,

#main > aside


{
background: beige;
}

#main > nav


{
order: -1;
}

Page | 79
header, footer
{
background: yellowgreen;
height: 20vh;
}

header, footer, article, nav, aside


{
padding: 1em;
}

@media screen and (min-width: 576px)


{
#main {
flex-direction: row;
}

#main > nav,

#main > aside


{
flex: 0 0 20vw;
}
}
</style>

<body>

<header>Header</header>

<div id="main">

<article>Article</article>

<nav>Nav</nav>

<aside>Aside</aside>

</div>

<footer>Footer</footer>

</body>

Page | 80
The layout still looks the same (which is good), but our media query now looks like this:

@media screen and (min-width: 576px)


{
#main {
flex-direction: row;
}

#main > nav,

#main > aside


{
flex: 0 0 20vw;
}
}

Page | 81
 And all the other code comes before it.

 Note that the media query uses min-width this time, to match all devices of that
width and wider.

 In the previous example we used max-width to match only devices that were that
width or narrower.

 So what we've done is set the initial layout's flex-direction to column, then for
larger devices, set it to row.

 We've also put the flex-basis back for the larger devices.

Page | 82
How to Align Form Elements with Flexbox

 Here is how you can use flexbox to align your form elements nice and evenly.

 Before flexbox came along, aligning form elements could be a bit tricky at times.

 However, flexbox simplifies this process quite considerably.

 Let us start with a quick example.

 Here is a form without flexbox.

<!doctype html>

<title> Example </title>

<style>
.wrapper {
background-color: whitesmoke;
list-style-type: none;
padding: 0;
border-radius: 3px;
}

.form-row {
padding: .5em;
}

.form-row > label {


padding: .5em 1em .5em 0;
}

.form-row > input,


.form-row > button {
padding: .5em;
}

.form-row > button {


background: gray;
color: white;
border: 0;
}
</style>

Page | 83
<form>

<ul class="wrapper">

<li class="form-row">

<label for="name">Name</label>

<input type="text" id="name">


</li>

<li class="form-row">

<label for="townborn">Town you were born in</label>

<input type="text" id="townborn">


</li>

<li class="form-row">

<label for="email">Email Address</label>

<input type="email" id="email">


</li>

<li class="form-row">

<button type="submit">Submit</button>

</li>
</ul>

</form>

Page | 84
 This form uses some light formatting, but the input fields are all the same width.

 This results in the right edge looking a bit jagged as the inputs do not line up directly
above each other.

 Now, if you are happy with that, fine. There is no need to go any further.

 But what if we want to have the input controls extend all the way to the right edge?

 Without flexbox, this would be a bit of a pain to get working properly.

 Especially if the form itself is fluid, (i.e. it expands/contracts depending on the width
of its parent or viewport).

 If the form is fluid, then each input control would also need to expand and contract
as required. In this case, you could not use a fixed width for the input controls
because as soon as the form's width changes, the width of the control would be
wrong.

 Therefore, you'd need to use a bit of trickery to get it all working correctly.

 However, flexbox allows you to do this without having to apply any magic tricks.

Page | 85
<!doctype html>

<title>Example</title>

<style>

.wrapper
{
background-color: whitesmoke;
list-style-type: none;
padding: 0;
border-radius: 3px;
}

.form-row
{
display: flex;
justify-content: flex-end;
padding: .5em;
}

.form-row > label


{
padding: .5em 1em .5em 0;
}

.form-row > input


{
flex: 1;
}

.form-row > input,

.form-row > button


{
padding: .5em;
}
.form-row > button
{
background: gray;
color: white;
border: 0;
}
</style>

<form>
Page | 86
<ul class="wrapper">

<li class="form-row">

<label for="name">Name</label>

<input type="text" id="name">

</li>

<li class="form-row">

<label for="townborn">Town you were born in</label>

<input type="text" id="townborn">

</li>

<li class="form-row">

<label for="email">Email Address</label>


<input type="email" id="email">
</li>

<li class="form-row">

<button type="submit">Submit</button>

</li>
</ul>

</form>

Page | 87
To do that, we first set each .form-row class to display: flex:

.form-row
{
display: flex;
justify-content: flex-end;
padding: .5em;
}

 Note that we also used justify-content: flex-end but this is optional.

 In this case it simply moves the button across to the right.

 And now that each form row is a flex container, we apply the following to the input
controls:

.form-row > input {


flex: 1;
}

 So by applying flex: 1 to the input controls, flexbox will make these controls use up
the available free space, after the labels have been allocated.

 Therefore, the labels remain at their normal width and any padding is retained.

 The input controls can then start where they normally would, and stretch all the way
to the end.

Same-Width Controls

You could modify the above example so that the left edge of the form controls all line up
too (as well as the right edge).

<!doctype html>

<title>Example</title>

<style>

.wrapper {

Page | 88
background-color: whitesmoke;
list-style-type: none;
padding: 0;
border-radius: 3px;
}

.form-row {
display: flex;
justify-content: flex-end;
padding: .5em;
}

.form-row > label {


padding: .5em 1em .5em 0;
flex: 1;
}

.form-row > input {


flex: 2;
}

.form-row > input,

.form-row > button {


padding: .5em;
}

.form-row > button {


background: gray;
color: white;
border: 0;
}

</style>

<form>

<ul class="wrapper">

Page | 89
<li class="form-row">

<label for="name">Name</label>
<input type="text" id="name">
</li>

<li class="form-row">

<label for="townborn">Town you were born in</label>


<input type="text" id="townborn">
</li>

<li class="form-row">

<label for="email">Email Address</label>


<input type="email" id="email">
</li>

<li class="form-row">

<button type="submit">Submit</button>
</li>

</ul>
</form>

 This sets the controls to twice the width of the labels.

 You can adjust this depending on the form's width/expected width.

 For example you could use a 1/3 ratio or a 1/4 ratio for wider forms.

 If you are using a fixed width form, you can set one ratio that best suits the form.

 If it is a fluid form that changes width based on the width of the viewport, then you
could use media queries to set a different ratio for each breakpoint.

Page | 90
Same-Width Controls but Responsive

 Here's an example with media queries that change the ratio as the viewport size
changes.

<!doctype html>
<title>Example</title>
<style>
.wrapper {
background-color: whitesmoke;
list-style-type: none;

Page | 91
padding: 0;
border-radius: 3px;
}
.form-row {
display: flex;
justify-content: flex-end;
padding: .5em;
}
.form-row > label {
padding: .5em 1em .5em 0;
flex: 1;
}
.form-row > input {
flex: 2;
}
.form-row > input,
.form-row > button {
padding: .5em;
}
.form-row > button {
background: gray;
color: white;
border: 0;
}
@media screen and (min-width: 768px) {
.form-row > input {
flex: 3;
}
}
@media screen and (min-width: 992px) {
.form-row > input {
flex: 4;
}
}
@media screen and (min-width: 1200px) {
.form-row > input {
flex: 5;
}
}
</style>
<form>
Page | 92
<ul class="wrapper">
<li class="form-row">
<label for="name">Name</label>
<input type="text" id="name">
</li>
<li class="form-row">
<label for="townborn">Town you were born in</label>
<input type="text" id="townborn">
</li>
<li class="form-row">
<label for="email">Email Address</label>
<input type="email" id="email">
</li>
<li class="form-row">
<button type="submit">Submit</button>
</li>
</ul>
</form>

 If you resize the browser down. You should see the form controls adjusting their
width as you shrink the browser window.

 This assumes you are not already viewing this on a smaller device.

 If you are, try this out when you get to a larger one.

Page | 93
Page | 94

You might also like