Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

CSS-Recap

Module 3 introduces CSS (Cascading Style Sheets) as a method to style HTML web pages, covering its syntax, selectors, combinators, and insertion methods. It explains the CSS box model, sizing elements, specificity, and style hierarchy to help users create visually appealing web designs. The module also includes practical exercises to reinforce learning about CSS concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

CSS-Recap

Module 3 introduces CSS (Cascading Style Sheets) as a method to style HTML web pages, covering its syntax, selectors, combinators, and insertion methods. It explains the CSS box model, sizing elements, specificity, and style hierarchy to help users create visually appealing web designs. The module also includes practical exercises to reinforce learning about CSS concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

1

Module 3
Do it with style!
Now, that you have already created a structure of your web page using HTML. We are now
left with a plain and boring black text pushed to the left side of a page with a white
background. Hence, we need to put some style into it to give it an enticing look and that is
where CSS comes in.

CSS (Cascading Style Sheets) is the code that styles web content. It answers questions like:
How do I make text green? How do I make content display at a certain location in the
(webpage) layout? How do I decorate my webpage with background images and colors? Let’s
now have a walkthrough on some CSS basics to know what you need to get started.

What’s in this Module?


What is CSS? ............................................................................................................................................... 2
CSS Selectors ............................................................................................................................................... 3
CSS Combinators ......................................................................................................................................... 5
CSS Insertion ............................................................................................................................................... 6
The CSS box model...................................................................................................................................... 8
CSS Sizing .................................................................................................................................................. 10
CSS Specificity and Style Hierarchy ........................................................................................................... 11
CSS Reset .................................................................................................................................................. 13
CSS Layout – The display Property ............................................................................................................ 16
CSS Layout – The position Property .......................................................................................................... 21
Centering elements using CSS ................................................................................................................... 22
CSS Fonts .................................................................................................................................................. 25
CSS typography ......................................................................................................................................... 29
CSS float and clear .................................................................................................................................... 31
CSS Best Practices ..................................................................................................................................... 33
2

What is CSS?

CSS stands for Cascading Style Sheets. Like HTML, CSS is not a programming language. It's
not a markup language either. CSS is a style sheet language. CSS is what you use to selectively
style HTML elements. In fact, it describes how HTML elements are to be displayed on screen,
paper, or in other media. CSS can control the layout of multiple web pages all at once allowing
you to save a lot of work. External stylesheets are stored in CSS files that bears the .css
extension.

CSS Syntax

A CSS rule consists of a selector and a declaration block.


Ruleset

Fig 1. Structure of CSS Ruleset

The whole structure is called a ruleset or often referred to as just rule. The selector points
to the HTML element you want to style. The declaration block contains one or more
declarations separated by semicolons. Each declaration includes a CSS property name and a
value, separated by a colon. Multiple CSS declarations are separated with semicolons, and
declaration blocks are surrounded by curly braces.

Example

Explanation:

 p is a selector in CSS (it points to the HTML


element you want to style: <p>).
 color is a property, and green is the
property value
 text-align is a property, and center is the
property value
3

CSS Selectors

CSS selectors are used to “target” the HTML elements you want to style. There are several
types of selectors in CSS as follows:

1. The element/type selector


Here, all <p> elements on the page will be center-aligned, with a green text color:

css

2. The id selector

The CSS rule below will be applied to the HTML element with id="para1":

css

3. The class selector


In this example all HTML elements with class="center" will be red and center-
aligned:
css

Note: A class name cannot start with a number.


4

4. The attribute selector

This group of selectors gives you different ways to select elements based on the
presence of a certain attribute on an element:

5. The Pseudo-class selector


This selector selects elements according to its state as defined by a pseudo-class. An
example of this is using the :hover pseudo-class on a <a> element:

List of commonly used pseudo-classes are as follows:

Pseudo-class Description
:link Use this class to add special style to an unvisited link.
:visited Use this class to add special style to a visited link.
:hover Use this class to add special style to an element when
you mouse over it.
:active Use this class to add special style to an active element.
:focus Use this class to add special style to an element while the
element has focus.
:first-child Use this class to add special style to an element that is
the first child of some other element.
:lang Use this class to specify a language to use in a specified
element.
5

CSS Combinators

Each type of selector discussed in the previous section can be combined to make a
combinator selector. Meaning, the class selector, id selector or even element selectors, can
be combined together to target an element which you want to style.

There are four different combinators in CSS:

1. Descendant selector (space)

Its basically selects all the elements inside or descendant to the specified element. For
instance, you have this ruleset and html elements.

div p { <div>
color : red; <p>Paragraph</p>
} <h1><p>Nested Paragraph</p><h1>
</div>

Result: It will apply the color style to all the <p> elements inside <div> elements
including all nested <p> elements, such as the one inside an <h1> element.

2. Child selector (>)

Its selects all the elements inside the specified element excluding the nested elements.
For instance, the CSS below applied to the same html elements.

div > p {
color : red;
}

Result: It selects all the <p> elements of <div> element but it will not affect the
nested <p> elements.

3. Adjacent sibling selector (+)

It selects the elements the just after element of the specified element. For instance,

div + p { <div>
color : red; <p>Paragraph 1</p>
} <h1><p>Nested Paragraph</p><h1>
</div>
<p>Paragraph 2</p>

Result: So the above code will only select the <p> element which is just after
the <div> element.
6

4. General sibling selector (~)

It selects all the elements after the specified element. For instance,

div ~ p { <div>
color: red; <p>Paragraph 1</p>
} <h1><p>Nested Paragraph</p><h1>
</div>
<p>Paragraph 2</p>
<span>This is a span</span>
<p>Paragraph 3</p>

Result: It will select all the <p> elements after the <div> element.

A combinator is something that explains the relationship between the selectors.

Suggested Readings

1. https://dev.to/kunaal438/css-combinators-all-about-css-selector-learn-css-2022-4i9f

CSS Insertion

There are three ways of inserting a style sheet:

1. External CSS
In external stylesheet you can just have one file to change the look of an entire
website. Each HTML page must include a reference to the external style sheet file
inside the <link> element, inside the head section.

index.html

mystyle.css

Note: The external .css file should not contain any HTML
tags.
7

2. Internal CSS

An internal style sheet may be used if one


single HTML page has a unique style.

The internal style is defined inside the


<style> element, inside the <head> section
of an HTML page.

Attributes associated with <style> elements:


Attribute Value Description
type text/css Specifies the style sheet language
as a content-type (MIME type). This
is required attribute.
Media Screen Specifies the device the document
Tty will be displayed on. Default value
Tv is all. This is an optional attribute.
Projection
Handheld
Print
Braille
Aural
all

3. Inline CSS
An inline style may be used to apply a unique style for a single element.
To use inline styles, add the style attribute to the relevant element. The style
attribute can contain any CSS property.
8

The CSS box model

The CSS box model is one of the fundamentals of website development. Understanding this
model will enable you to better align elements with other elements and create more complex
layouts. It is essentially a box that wraps around every HTML element. It consists of:
margins, borders, padding, and the actual content. CSS determines the size, position, and
properties (color, background, border size, etc.) of these boxes.

Every element in web design is a rectangular box.

Parts of a box

Making up a block box in CSS we have the:

 Content box: The area where your content is displayed, which can be sized using
properties like width and height.

 Padding box: The padding sits around the content as white space; its size can be
controlled using padding and related properties.

 Border box: The border box wraps the content and any padding. Its size and style
can be controlled using border and related properties.

 Margin box: The margin is the outermost layer, wrapping the content, padding, and
border as whitespace between this box and other elements. Its size can be controlled
using margin and related properties.
The diagram below shows the layers of the box model:

The Standard CSS box model

In the standard box model, if you give a box a width and a height attribute, this defines the
width and height of the content box. Any padding and border is then added to that width and
height to get the total size taken up by the box.
9

If we assume that a box has been defined with CSS ruleset below:

.box { css
width: 350px;
height: 150px;
margin: 10px;
padding: 25px;
border: 5px solid black;
}

The actual space taken up by the box will be 410px wide (350 +[25 + 25] + [5 + 5]) and
210px high (150 + [25 + 25] +[ 5 + 5])as shown by the figure on the right.

Note: The margin is not counted towards the actual size of the box — sure, it affects the total space
that the box will take up on the page, but only the space outside the box. The box's area stops at
the border — it does not extend into the margin.

The Alternative CSS box model

By default, browsers use the standard box model. If you want to turn on the alternative
model for an element, you do so by setting box-sizing: border-box on it. By doing this, you
are telling the browser to use the border box, as shown above, as your defined area.
css
.box {
box-sizing: border-box;
}

If you want all of your elements to use the alternative box model, and this is a common choice
among developers, set the box-sizing property on the <html> element, then set all other
elements to inherit that value, as seen in the snippet below. If you want to understand the
thinking behind this, see https://css-tricks.com/inheriting-box-sizing-probably-slightly-
better-best-practice/

html { css
box-sizing: border-box;
}
*, *::before, *::after {
box-sizing: inherit;
}

Exercise: Box Models


To further understand this concept, you can play around with box models in the link below.
https://vinc3isaac18.github.io/module%203/box-models.html
10

CSS Sizing

HTML Elements have a natural size, set before they are affected by any CSS. So, if there is no
CSS applied, any element will be displayed by ists intrinsic size. Otherwise, explicitly setting
a height or width value will dictate how the elements would appear in the screen in terms of
its size.

The natural or intrinsic size of things

HTML Elements have a natural size, set before they are affected by any CSS. A
straightforward example is an image. An image file contains sizing information, described as
its intrinsic size. This size is determined by the image itself, not by any formatting we happen
to apply. Hence, an image without applying any CSS will be displayed by its original
dimensions. However an element without a set height such as an empty <div> tag will have
no height since it has content but the width will be at full stretch in your browser.

Setting specific size to elements

Setting the size of the elements using CSS can be done in different ways for different
intentions. Basically, the two properties the affects the sizing of any element are height and
width. Thus, we can of course set these properties to give elements our desired size. This
size that we impose on the elements is referred to as extrinsic size.

.box { css
border: 5px solid teal;
width: 200px
height: 150px;
width: 200px;
}

Using percentages

In many ways, percentages act like length units and they can often be used interchangeably
with lengths. When using a percentage you need to be aware what it is a percentage of. In the
case of a box inside another container, if you give the child box a percentage width it will be
a percentage of the width of the parent container.

.box { css .box { css


border: 5px solid teal; border: 5px solid teal;
width: 50%; width: 300px;
} margin: 10%;
padding: 10%;
}
11

min- and max- sizes

In addition to giving things a fixed size, we can ask CSS to give an element a minimum or a
maximum size. If you have a box that might contain a variable amount of content, and you
always want it to be at least a certain height, you could set the min-height property on it. The
box will always be at least this height, but will then grow taller if there is more content than
the box has space for at its minimum height.

.box {
border: 5px solid teal;
min-height: 150px;
width: 200px;
}

Exercise: Sizing Elements in CSS


To access the exercise in CSS sizing. Visit the web URL below.
https://vinc3Isaac18.github.io/module%203/box-sizing.html

CSS Specificity and Style Hierarchy

What is Specificity?

If there are two or more CSS rules that point to the same element, the selector with the
highest specificity value will "win", and its style declaration will be applied to that HTML
element.

Think of specificity as a score/rank that determines which style


declaration are ultimately applied to an element.

To understand how specificity works, try out the codes below. Do one after the other.

<html> html <html> html


<head> <head>
<style> <style>
p {color: red;} .test {color: green;}
</style> p {color: red;}
</head> </style>
<body> </head>
<p class="test">Hello World!</p> <body>
</body> <p class="test">Hello World!</p>
</html> </body>
</html>
12

What did you observe with the CSS applied to the <p> element in code at the right? What do
you think is the reason?

So, if your answer is something like a CSS rule is overriding other, then you are right! In fact,
that is how specificity basically affects the styling of the elements. But, there is more to know
than that fact. One thing is how the CSS rules go against each other to find out which gets
applied to a certain element and that is where specificity hierarchy comes into play.

Specificity Hierarchy

Every CSS selector has its place in the specificity hierarchy. There are four categories which
define the specificity level of a selector: (Arranged from highest to lowest priority)
 Inline styles - Example: <h1 style="color: pink;">
 IDs - Example: #navbar
 Classes, pseudo-classes, attribute selectors - Example: .test, :hover, [href]
 Elements and pseudo-elements - Example: h1, :before

Notes:
1. Inline style gets a specificity value of 1000, and is always given the highest priority!
2. There is one exception to this rule: if you use the !important rule, it will even override
inline styles!

How to Calculate Specificity?

Memorize how to calculate specificity! Start at 0, add 100 for each ID value, add 10 for each
class value (or pseudo-class or attribute selector), add 1 for each element selector or pseudo-
element.

Selector Specificity Value Calculation


p 1 1
p.test 11 1 + 10
p#demo 101 1 + 100
<p style="color: pink;"> 1000 1000
#demo 100 100
.test 10 10
p.test1.test2 21 1 + 10 + 10
#navbar p#demo 201 100 + 1 + 100
* 0 0 (the universal selector is ignored)
13

CSS Reset
There are two primary reasons why we reset the browser styles:

 Not all browsers apply the same default rules. They may be similar, but not exact.
It can be difficult to provide the same designs in each browser if the basic styles are
different.

 Once you start designing and coding all of the fine details of your site, you may
discover that a lot of what you are doing is simply overriding default browser
styles. The reset does this quickly so that you don't have to.

A CSS Reset style sheet is a list of rules that 'reset' all of


the default browser styles.

In implementing “CSS resets” in your web pages, we have two approaches:

 Nicolas Gallagher’s Normalize.css is the gentle approach. Normalize.css is fixing


differences between the implementation in different browsers.

 Eric Meyer’s CSS Reset is the hard approach, saying that in most cases we don’t want
basic styles from the browsers, like the font-size value we get from elements
like <h1> through <h6>, or the default styles for the <ul> and <ol> list elements.
For example, we use the list only for the semantic meaning, and because it helps in
other ways for accessibility and SEO.

Note: As alternative to Meyer’s CSS Reset, we can also use a “The New CSS Reset” created by
Elad Shechter.
14

Exercise: Applying CSS to HTML document

1. Go to your local GitHub repository and create a new folder named css. Within the
css folder, create a new text document called styles.css, and save it.

2. Download CSS reset files from the following links and save it in the same css folder.
 https://necolas.github.io/normalize.css/

3. Insert your external CSS files, add the following lines inside the <head> section.
<link rel="stylesheet" href="normalize.css" media="screen"> css
<link rel="stylesheet" href="resets.css" media="screen">
<link rel="stylesheet" href="styles.css" media="screen">

Note: The CSS files should be inserted in the order shown above.

4. Check what elements do we have so far inside the <body> of your html document.
At this point we should have the following:
 <header>  <img>
 <ul>  <figcaption>
 <li>  <div>
 <a>  <h1>
 <figure>  <footer>

5. Replace the <div class="page-content"> … </div> section with the html


code below.
<div class="page-content">
<div class="card" id="about">
<p class="card-header">About</p>
<p class="card-body">Hello! Tell us about yourself.</p>
</div>
<div class="card" id="education">
<p class="card-header">Education</p>
<p class="card-body">Tell us about your education</p>
</div>
<div class="card" id="skills">
<p class="card-header">Skills</p>
<p class="card-body">Tell us about your IT Skills>
</div>
<div class="card" id="portfolio">
<p class="card-header">Portfolio</p>
<p class="card-body">Share your previous IT projects</p>
</div>
</div>
15

6. Add the following CSS rulesets in your styles.css file.

.page-content{
padding-top:30px;
overflow: hidden;
}
.card {
/* Add shadows to create the "card" effect */
border: 3px solid teal;
border-radius: 5px;
width: 70%;
margin-top:3%;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
transition: 0.3s;
}
.card-header{
padding:1%;
font-size: 20px;
font-weight: 700;
border-bottom: 2px solid rgb(192, 192, 192);
}
.card-body{padding:5%;}

/* On mouse-over, add a deeper shadow */


.card:hover {
box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2);
}

7. Make sure the HTML and CSS files are saved. Then load index.html in your browser.
You should see something like this:
16

What happened?

CSS was applied to style the <div> elements to my a card effect. Class selectors and a Pseudo-
class selector were used to target the <div> elements. Specifically, there are four classes page-
content, card, card-header, and card-body. Morever, the :hover pseudo-class was targeted to
inject a shadowing effect once the mouse pointer is hovered on the cards.

Suggested Readings
1. https://developer.mozilla.org/en-US/docs/Web/CSS/Layout_cookbook/Card

CSS Layout – The display Property


Always remember, every element on a web page is a rectangular box. The display property
in CSS determines just how that rectangular box behaves. Hence it is the most important CSS
property for controlling layout.

span { css The css ruleset at the left is a sample usage of


display: inline-block; display property on a <p> element. The default
} display value for most elements is block or inline.

Block-level Elements
A block-level element always starts on a new line and takes up the full width available
(stretches out to the left and right as far as it can).

Examples of block-level elements:


 <div>  <header>
 <h1> - <h6>  <footer>
 <p>  <section>
 <form>
Inline Elements

Elements like <span>, <a>, <img>, <em>, or <b> are examples of inline elements. Thus,
wrapping text in those elements within a string of text doesn’t break the flow of the text.

Note: display: none, hides the element from the screen. It is commonly used with JavaScript
to hide and show elements without deleting and recreating them.
17

The display: inline-block Value

One common use for display: inline-block is to display list items horizontally instead
of vertically as you can see in the illustration below.

inline-block

block

Exercise: Using the display property

1. Go to your local repository and create a new folder named css. Within the css folder,
create a new text document called styles.css, and save it.

2. In your index.html, add a nav class to the <ul> tag same as in the code below.

<ul class="nav"> html


<li><a href="#about">About</a></li>
<li><a href="#education">Education</a></li>
<li><a href="#skills">Skills</a></li>
<li><a href="#portfolio">Portfolio</a></li>
<li><a href="#contact">Contact</a></li>
</ul>

3. Now in your styles.css file, add the following CSS rulesets.

.nav{ css
background-color: teal;
list-style-type: none;
}

.nav li{
display: inline-block;
font-size: 20px;
padding: 20px;
}

.nav li a{
text-decoration: none;
color:white
}
18

4. Make sure the HTML and CSS files are saved. Then load index.html in your browser.
You should see something like this:

Display: flex (Flexbox) vs. display: grid (Grid layout)

A website layout is often comprised by headers, menus, content and a footer. In the past,
developers have to “hack” their CSS, using table elements, in-line blocks, floats, and different
positioning types to create such layout. Some complex layouts may even require JavaScript
as well.

Hence, to simplify both the creation and maintenance of web pages, responsive layout
models were created. Among the most popular are Flexbox, CSS Grid, and Bootstrap, each of
which are widely supported across platforms and browsers.

Flexbox and Grid are two CSS layout models that can be used to create complex
web application layouts with just a couple of CSS rules.

How CSS Flexbox layout works

The Flexbox (or Flexible Box) layout model is a one-dimensional CSS layout model that
allows you to create responsive layouts for your web application.

With Flexbox, you can lay out and align elements in a container even if you don’t know the
size of those elements or if the size might change. That’s because a flex container is flexible:
19

it expands the flex elements to fill space when it’s available and shrinks them to prevent
overflow when it’s not.

Flexbox strengths31

1. Layout control in 1-dimension, vertically or horizontally


2. Adjust justification and alignment
3. Override alignment for child element settings

To enable the flexbox layout in your elements, you need to add the CSS display:
flex property to your container element as follows:

<div class="container"> .container {


<div class="item">1</div> display:flex;
<div class="item">2</div> flex-wrap: nowrap;
<div class="item">3</div> gap: 20px;
<div class="item">4</div> }
<div class="item">5</div> .item{
</div> Background-color: teal;
Padding:3em;
}

Note: To specify that the flexible items will wrap if


necessary use flex-wrap: wrap;
Output:

How CSS Grid layout works

The CSS Grid layout allows you to create a two-dimensional layout model that is made of
rows and columns. It allows you to create a much more rigid layout for your web page that
doesn’t change based on the content size.
20

With CSS Grid, you can align components into columns and rows. This makes it ideal for
larger layouts that need to be divided into sections. In other words, this type of layout will
have elements that need to overlap and layer, rather than be linear.

Grid strengths

1. Layout control in 2-dimension, vertically and horizontally


2. Organize elements anywhere inside grid cells
3. Adjust positioning
4. Override alignment on child element settings

To enable the grid layout in your elements, you need to add the CSS display:
grid property to your container element as follows:
Output:
.container {
display:grid;
grid-template-columns: auto auto auto;
gap: 20px;
}
.item{
Background-color: teal;
Padding:3em;
}

Note: To specify the number and the widths of columns in the grid,
use grid-template-columns property.

Recommended Use Cases

Now, that you understand the differences between Flexbox and Grid CSS layout models, let’s
go over some recommendations on when to use one over the other.

1. Grid is great If you can break your design into a grid


2. Flexbox is great if your design spans either horizontally or vertically
3. Grid allows for breakpoints in responsive design
4. Grid and Flexbox are both excellent tools
5. Pick the tools that best suit what you’re trying to build

Suggested Readings

1. https://www.w3schools.com/cssref/css3_pr_flex-wrap.asp
21

CSS Layout – The position Property

The position property specifies the type of positioning method used for an element. It can
help you manipulate the location of an element

The position Property

The position property specifies the type of positioning method used for an element.

There are five different position values:


 static : every element has a static position by default, so the element will stick to
the normal page flow. So if there is a left/right/top/bottom/z-index set then there
will be no effect on that element.
 relative : an element’s original position remains in the flow of the document, just
like the static value. But now left/right/top/bottom/z-index will work. The positional
properties “nudge” the element from the original position in that direction.
 fixed : the element is removed from the flow of the document like absolutely
positioned elements. In fact they behave almost the same, only fixed positioned
elements are always relative to the document, not any particular parent, and are
unaffected by scrolling.
 absolute : the element is removed from the flow of the document and other
elements will behave as if it’s not even there whilst all the other positional properties
will work on it.
 sticky : the element is treated like a relative value until the scroll location of the
viewport reaches a specified threshold, at which point the element takes
a fixed position where it is told to stick.
 inherit : the position value doesn’t cascade, so this can be used to specifically force
it to, and inherit the positioning value from its parent.

Suggested Readings

1. https://css-tricks.com/almanac/properties/p/position/
2. https://www.geeksforgeeks.org/css-positioning-elements/
22

Exercise: Using the position property

Using the position property let us make the navbar stick at the top even during scroll down.
1. Add the line position: fixed; top:0; width:100%; in the nav class ruleset as
shown below.
.nav{ css
background-color: teal;
list-style-type: none;
text-align: center;
position: fixed; top:0; width:100%;
}

2. Scroll the page back and forth and observe the behavior of the navigation bar.

Centering elements using CSS

Centering things is one of the most difficult aspects of CSS. The methods themselves usually
aren't difficult to understand. Instead, it's more due to the fact that there are so many ways
to center things.

Horizontal Centering
Centering elements horizontally is generally easier than centering them vertically. Here are
some common elements you may want to center horizontally and different ways to do it.
 Center Text with the CSS Text-Align Center Property
23

To move the encircled texts to the center, we can add text-align:center in the
nav and card-header classes.

Now, we should see the texts at the center,

.nav{ css
background-color: teal;
list-style-type: none;
position: fixed; top:0; width:100%;
text-align: center;
}
. . . . .
.card-header{
padding:1%;
font-size: 20px;
font-weight: 700;
border-bottom: 2px solid rgb(192, 192, 192);
text-align: center;
}

 Center a Div with CSS Margin Auto


24

To move the all the <div> contents to the center, we add margin: 0 auto in the
card class ruleset.

.card { css
/* Add shadows to create the "card" effect */
border: 3px solid teal;
border-radius: 5px;
width: 70%;
margin-auto: 0 auto;
margin-top:3%;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
transition: 0.3s;
}

 Center a Div Horizontally with Flexbox

If we apply this method to the same example, flexbox is not recommended since we
have multiple divs stacked together in our web page. Instead of centering the div
elements it will arrange them side by side or in an in-line fashion. However, it will work
when centering a single div inside another div container. You will just add these two
lines in the class of the div container:
Vertical Centering
Centering elements vertically without modern methods like Flexbox can be a real chore.
This is how to do it with Flexbox.
 Center a Div Vertically with Flexbox
.container { css
/* Center child div horizontally*/
display: flex;
justify-content: center;
}

The same with the caution given previously, this will not work with multiple stacked
divs. However, when having only a single div element inside a div container. You will
just add these two lines in the class of the div container:

.container { css
/* Center child div vertically*/
display: flex;
align-items: center;
}

Suggested Readings
1. https://www.freecodecamp.org/news/how-to-center-anything-with-css-align-a-div-text-
and-more/
25

CSS Fonts
When talking about fonts, we need to clarify some terminologies:
 Typeface: The design of a collection of glyphs (e.g. letters, numbers, symbols)
 Font: A specific size, weight, or style of a typeface (e.g. regular, bold, italic)
Font selection is important in website design. Choosing the right font has a huge impact on
the user’s experience in viewing a website. Fonts can tell so much about the identity of your
website which establishes your brand. Creativity is encouraged but using a easy to read fonts
is key. Moreover, color and text size are also properties that needs consideration.

Font Family
In CSS, there are basically five(5) font families:
1. Serif fonts have a small stylish stroke at the edges of each letter. They create a sense of
formality and elegance.

2. Sans-serif fonts have plain letters, no stroke. They provide a modern and minimalistic
look.
26

3. Monospace fonts - fonts are fixed-pitch, fixed-width letters. They create a mechanical
look. Mostly used to represent the programming code

4. Script/Cursive fonts similar to human handwriting.

5. Fantasy fonts are decorative/playful fonts/fancy look.

We use the font-family property to set the specific font we want to apply to our website as
follows.

.p1 { css
font-family: "Times New Roman", Times, serif;
}

Note: If the font name is more than one word, it must be in quotation
marks, like: "Times New Roman".
27

How to choose fonts and font pairings?

This is subjective and depends on what you’re trying to do. Each typeface has its own
personality, so you’ll have to find one that aligns with your brand or the content it’s
communicating. Typefaces have to be considered within the context that they’re being
applied. Are we looking for formality? Maybe start with the serif family. Warm, fun and
friendly? That might be a cue for sans-serif. Just know that there is no hard science to
choosing a font, and even the most trained of typographers are considering contextual cues
to find the “right” one.

The only way to find out if two fonts are complementary is to see them together. Tools
like FontPair and TypeConnection can help with this. If a font catches your eye when
surfing the web, WhatFont is a great browser extension to help identify it. Another great
resource is Typewolf which allows you to see examples of great web typography.

Font Weight

Some font families have a wide range of font weights — Light, Book, Regular, Medium,
Semi-Bold, Bold, Black — whereas others just have a couple.

If you’re building a complex web app UI, you might need a range of font weights to establish
hierarchy in different contexts. For something less complex, say a blog, you’ll likely be fine
with just a couple.

Font Style

Fonts come in a variety of styles. Good fonts


have specific bold and italic styles.

These faux styles tend to reduce legibility


and break the text’s visual cohesion because
the browser can only do so much with what
it’s given. Stick to fonts that offer true
bold/italics styles, if you can.
28

Web Safe Fonts

Web safe fonts are fonts that are universally installed across all browsers and devices, which
means no matter where the person is in the world and what device they’re using, a websafe
font will always load and display correctly.
The following fonts are the best web safe fonts for HTML and CSS:
 Arial (sans-serif)  Times New Roman (serif)
 Verdana (sans-serif)  Georgia (serif)
 Helvetica (sans-serif)  Garamond (serif)
 Tahoma (sans-serif)  Courier New (monospace)
 Trebuchet MS (sans-serif)  Brush Script MT (cursive)

In spite having Web safe fonts, they are not 100% guaranteed. There is always a chance that
a font is not found or is not installed properly. Therefore, it is very important to always use
fallback fonts. This means that you should add a list of similar "backup fonts" in the font-
family property. If the first font does not work, the browser will try the next one, and the next
one, and so on. Always end the list with a generic font family name.

font-family property should hold several font names as a "fallback" system


to ensure maximum compatibility between browsers/operating systems.

Google Fonts

One way to use any of the standard fonts in HTML, is through Google Fonts. It are free to use,
and have more than 1000 fonts to choose from. For the full list of Google fonts, you can access
it at https://fonts.google.com/

To use Google Fonts, for example the font “Open Sans”, we can do something like,

<head> css
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open Sans">
<style>
body {
font-family: "Open Sans", "Segoe UI", Tahoma, sans-serif;
}
</style>
</head>

Here is a caveat, Google Fonts is full of awesome and free fonts, but unfortunately, using them
means that you need to load a separate file. Usually this doesn’t affect the loading speed of
your pages, but in rare cases (especially on slower connections) it definitely can have a
noticeable effect on the user experience. To address such cases, you can combine online fonts
with website friendly fonts in your “font stack.”
29

Suggested Readings

1. https://developer.mozilla.org/en-US/docs/Web/CSS/font
2. https://wpastra.com/web-safe-fonts/
3. https://alistapart.com/article/say-no-to-faux-bold/
4. https://www.cssfontstack.com/

CSS typography
Typography is an essential component of a website’s design. This is for good reason: good
typography is not only imperative for aesthetic appeal, but also improves site usability when
text legibility and readability concepts are applied. Typography is all about proportions and
spacing.

There are two main groups of CSS properties that control typography style: font and text.
The font CSS property group dictates general font characteristics such as font-
style and font-weight. Below you’ll see the p element given a font-style and a font-
weight property.

p {
font-style: oblique;
font-weight: bold;
}

Adjusting Font Sizing

Browser compatibility is a major issue in web design, even more so if you are attempting to
make your web designs look the same in all browsers. Beginning web designers may mess
around with a font’s size until it looks just right, only to find it has completely changed among
other browsers and platforms. Size fonts the correct way, and this problem can be
minimized.

A simple use of sizing text is as follows:


h6 { font-size: 12pt; }

The above sets the heading level-6 element to 12pt. For font-size values, there are 4 types of
units of measurement.
30

Units of measure in Sizing

There are 15 different units for sizing in CSS? But, most of us are probably aware of and
comfortable working with pixels (px) but there are so many other ways we can define the
size of a font. Some of these are relative units, and others are absolute. The actual size of an
element expressed in relative units depends on other parts of the page, while the actual size
of an element expressed in absolute units is always the same. And, as you might expect, that
difference is important because they serve different functions, depending on a design’s
needs.

Of the 15 units available, we will selectively look at two in particular: px and em.

 px
px is an absolute unit and it actually doesn’t have much to do with pixels, but it’s
defined so that a line of width 1px appears sharp and visible, no matter the screen
resolution. When it comes to typrography, px is a unit to be understood, but not
used. The true purpose of px units is to serve as the foundation of a type system based
on relative units. In other words, it’s an absolute value that a relative unit can point
to in order to define its own size relative to that value.

 em
em is a relative unit. Text with a font size of 2em would be twice as big as the font-
size of its parent element. The em lets you reason about your typography intuitively:
“I want this title to be twice as big as the paragraph text” corresponds directly to 2em.
It’s also easy to maintain — if you need a media query to make everything bigger on
mobile, it’s a simple matter of increasing one font-size attribute.

Important CSS properties for Typography


31

Line height is one of the most important factors affecting readability. It’s controlled by
the line-height property, best expressed as a unit-less number that corresponds to a multiple
of the defined font size. Here are some general guidelines to define a good line-height:
 Increase line-height for thick fonts
 Increase line-height when fonts are a dark color
 Increase line-height for long-form content

Letter spacing is one of the most important factors affecting legibility. It is controlled by the
CSS letter-spacing property, best expressed (again) in em units to keep everything relative.
Tracking (the typography term for “letter spacing”) depends entirely on the font — some
fonts will look great by default, while others might need a little tweaking.

Using absolute units Using relative units/unitless value


p { p {
font-style: normal; font-style: normal;
font-size: 16px; font-size: 1em;
font-weight:700; font-weight: 700;
line-height: 32px; line-height: 1.5;
letter-spacing: 1px; letter-spacing: 0.2em;
} }

Note: In line-height, unitless number value that is multiplied by the element's font size.

Suggested Readings
1. https://www.webfx.com/blog/web-design/20-websites-with-beautiful-typography/
2. https://css-tricks.com/typography-for-developers/

CSS float and clear

Before flexbox and grid, CSS float property are used to make grids and layouts.
Moreover, floats are also used in wrapping text around images, just like in a print layout as
shown below.

Float
Left

Float Right
32

The float property can be specified with any of the following values:
 none (default): The element doesn’t float. It is simply displayed where it occurs in the
text.
 left: The element floats to the left of its container.
 right: The element floats to the right of its container.
 inherit: The element inherits the float value of its parent.

Example:

.img-right {
float: right;
}

The CSS clear property is directly related to the float property. It specifies if an element
should be next to the floated elements or if it should move below them. This property applies
to both floated and non-floated elements.

The clear property can have following values:


 None - the element is not moved down to clear past floats.
 Left - the element is moved down to clear past left floats.
 Right - the element is moved down to clear past right floats.
 Both - the element is moved down to clear past both left and right floats.

Example:

.img-right {
clear: both;
}

Exercise: Using float and clear properties


To further understand this concept, you can play around with box models in the link below.
https://vinc3isaac18.github.io/module%203/float-clear.html
33

CSS Best Practices

Here are some general suggestions for ways to keep your stylesheets organized and tidy.

 Keep it consistent

If you get to set the rules for the project or are working alone, then the most important
thing to do is to keep things consistent. Consistency can be applied in all sorts of ways,
such as using the same naming conventions for classes, choosing one method of
describing color, or maintaining consistent formatting. (For example, will you use
tabs or spaces to indent your code? If spaces, how many spaces?)

 Formatting readable CSS

There are a couple of ways you will see CSS formatted. Some developers put all of the
rules onto a single line, like so:

.box { background-color: #567895; }


h2 { background-color: black; color: white; }

Other developers prefer to break everything onto a new line:

.box {
background-color: #567895;
}

h2 {
background-color: black;
color: white;
}

CSS doesn't mind which one you use. We personally find it is more readable to have
each property and value pair on a new line.

 Comment your CSS

Adding comments to your CSS will help any future developer work with your CSS file,
but will also help you when you come back to the project after a break.

/* This is a CSS comment


It can be broken onto multiple lines. */
34

A good tip is to add a block of comments between logical sections in your stylesheet
too, to help locate different sections quickly when scanning it, or even to give you
something to search for to jump right into that part of the CSS. If you use a string that
won't appear in the code, you can jump from section to section by searching for it —
below we have used ||.

/* || General styles */
...
/* || Typography */
...
/* || Header and Main Navigation */
...

 Create logical sections in your stylesheet

It is a good idea to have all of the common styling first in the stylesheet. This means
all of the styles which will generally apply unless you do something special with that
element. You will typically have rules set up for:

 body  ul and ol
 p  The table properties
 h1, h2, h3, h4, h5  Links

 Avoid overly-specific selectors

If you create very specific selectors, you will often find that you need to duplicate
chunks of your CSS to apply the same rules to another element. For example, you
might have something like the below selector, which applies the rule to a <p> with a
class of box inside an <article> with a class of main.

article.main p.box {
border: 1px solid #ccc;
}

If you then wanted to apply the same rules to something outside of main, or to
something other than a <p>, you would have to add another selector to these rules or
create a whole new ruleset. Instead, you could use the selector .box to apply your rule
to any element that has the class box:

.box {

border: 1px solid #ccc;

}
35

There will be times when making something more specific makes sense; however,
this will generally be an exception rather than usual practice.

 Break large stylesheets into multiple smaller ones

In cases where you have very different styles for distinct parts of the site, you might
want to have one stylesheet that includes all the global rules, as well as some smaller
stylesheets that include the specific rules needed for those sections. You can link to
multiple stylesheets from one page, and the normal rules of the cascade apply, with
rules in stylesheets linked later coming after rules in stylesheets linked earlier.

Congratulations! You have reached a major milestone. At this point, if you


have already completed all tasks for this module, you have now applied CSS
styling in your HTML document. Well, this just the beginning and continue
your learning about advance topics in CSS such as responsive and fluid
website design. The next module will focus on making your website
Milestone
interactive using JavaScript.

You might also like