Understanding CSS: Basics and Usage
Understanding CSS: Basics and Usage
h1 {
color: white;
text-align: center;
}
p{
font-family: verdana;
font-size: 20px;
}
• CSS Solved a Big Problem
• HTML was NEVER intended to contain tags for formatting a web page!
• HTML was created to describe the content of a web page, like:
• <h1>This is a heading</h1>
• <p>This is a paragraph.</p>
• When tags like <font>, and color attributes were added to the HTML
3.2 specification, it started a nightmare for web developers.
Development of large websites, where fonts and color information
were added to every single page, became a long and expensive
process.
• To solve this problem, the World Wide Web Consortium (W3C)
created CSS.
• CSS removed the style formatting from the HTML page!
CSS Syntax
• Example Explained
• p is a selector in CSS (it points to the HTML element you want to style: <p>).
• color is a property, and red is the property value
• text-align is a property, and center is the property value
CSS Selectors
• A CSS selector selects the HTML element(s) you want to style.
•
We can divide CSS selectors into five categories:
• Simple selectors (select elements based on name, id, class)
• Combinator selectors (select elements based on a specific relationship between
them)
• Pseudo-class selectors (select elements based on a certain state)
• Pseudo-elements selectors (select and style a part of an element)
• Attribute selectors (select elements based on an attribute or attribute value)
• The CSS element Selector
• The element selector selects HTML elements based on the element name.
• Example
• Here, all <p> elements on the page will be center-aligned, with a red text color:
• p{
text-align: center;
color: red;
}
• The CSS id Selector
• The id selector uses the id attribute of an HTML element to select a specific
element.
• The id of an element is unique within a page, so the id selector is used to select
one unique element!
• To select an element with a specific id, write a hash (#) character, followed by the
id of the element.
• Example
• The CSS rule below will be applied to the HTML element with id="para1":
• #para1 {
text-align: center;
color: red;
}
• The CSS class Selector
• The class selector selects HTML elements with a specific class attribute.
• To select elements with a specific class, write a period (.) character, followed by the class
name.
• Example
• In this example all HTML elements with class="center" will be red and center-aligned:
• .center {
text-align: center;
color: red;
}
• The CSS class Selector
• The class selector selects HTML elements with a specific class attribute.
• To select elements with a specific class, write a period (.) character, followed by the class
name.
• Example
• In this example all HTML elements with class="center" will be red and center-aligned:
• .center {
text-align: center;
color: red;
}
• The CSS Grouping Selector
• The grouping selector selects all the HTML elements with the same style definitions.
• Look at the following CSS code (the h1, h2, and p elements have the same style definitions):
• h1 {
text-align: center;
color: red;
}
h2 {
text-align: center;
color: red;
}
p{
text-align: center;
color: red;
}
•
Location of styles
Three Ways to Insert CSS
• There are three ways of inserting a style sheet:
• External CSS
• Internal CSS
• Inline CSS
• External CSS
• With an external style sheet, you can change the look of an entire website by changing just one
file!
• Each HTML page must include a reference to the external style sheet file inside the <link> element,
inside the head section.
• Example
• External styles are defined within the <link> element, inside the <head> section of an HTML page:
• <!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="mystyle.css">
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
• An external style sheet can be written in any text editor, and must be saved with
a .css extension.
• The external .css file should not contain any HTML tags.
• Here is how the "mystyle.css" file looks:
• "mystyle.css"
• body {
background-color: lightblue;
}
h1 {
color: navy;
margin-left: 20px;
}
• 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.
• <!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: linen;
}
h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
• 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.
• Example
• Inline styles are defined within the "style" attribute of the relevant element:
• <!DOCTYPE html>
<html>
<body>
</body>
</html>
.
• Multiple Style Sheets
• If some properties have been defined for the same selector (element) in different style sheets, the value from the last
read style sheet will be used.
• Assume that an external style sheet has the following style for the <h1> element:
• h1 {
color: navy;
}
• Then, assume that an internal style sheet also has the following style for the <h1> element:
• h1 {
color: orange;
}
• Example
• If the internal style is defined after the link to the external style sheet, the <h1>
elements will be "orange":
• <head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<style>
h1 {
color: orange;
}
</style>
</head>
• Cascading Order
• What style will be used when there is more than one style
specified for an HTML element?
• All the styles in a page will "cascade" into a new "virtual"
style sheet by the following rules, where number one has the
highest priority:
• Inline style (inside an HTML element)
• External and internal style sheets (in the head section)
• Browser default
• So, an inline style has the highest priority, and will override
external and internal styles and browser defaults.
Cascade
• We've already talked about how there can be many different sources of CSS styles. How do
we know which one will be used?
• In CSS, styles sheets cascade by order of importance. If rules in different style sheets
conflict with one another, the rule from the most important style sheet wins.
• Below is a list of possible sources of a CSS rule. They are listed by order of importance. As
the creator of the style sheet, you're the author.
• Author inline styles
• Author embedded styles (aka: internal style sheets)
• Author external style sheet
• User style sheet
• Default browser style sheet
• We've already seen the cascade in action. All browsers have a default style sheet, which is
designated as the least important.
• Whenever we define a CSS rule, like font-family, we are actually overriding a default
browser style sheet rule. This is the cascade in action.
• What happens when conflicts occur?
• There may be times when two or more declarations are applied to the same
element. It is also possible that there may be a conflict between them. When
conflicts like this occur, the declaration with the most weight is used. So, how is
weight determined?
• The Cascade Rules
• Find all declarations whose selectors match a particular element.
• Sort these declarations by weight and origin
• Sort the selectors by specificity
• Sort by order specified
• CSS Order Matters
• In CSS, the order in which we specify our rules matters.
• If a rule from the same style sheet, with the same level of specificity exists, the rule that is
declared last in the CSS document will be the one that is applied.
• An example will illustrate this best.
• 1. p {color: black;}
• 2. ul {border: 1px solid pink;}
• 3. p.intro {color: brown;}
• 4. p {color: red;}In the code above, we have created rules for paragraphs to be three different
colors.
• Clearly, these rules conflict with one another.
• Rule #3 is the most specific because it specifies all paragraphs that also have the class attribute
value of intro.
• Rules #1 and #4 conflict. They are from the the same style sheet and they have the same level of
specificity. If all else is equal in the cascade, we sort by order specified.
• Rule #4 is declared last in the CSS document and therefore, overrides the previously declared Rule
#1.
The CSS Box Model
The CSS Box Model
• In CSS, the term "box model" is used when talking about design and layout.
• The CSS box model is essentially a box that wraps around every HTML element. It consists of:
margins, borders, padding, and the actual content. The image below illustrates the box model:
• Explanation of the different parts:
• Content - The content of the box, where text and images appear
• Padding - Clears an area around the content. The padding is transparent
• Border - A border that goes around the padding and content
• Margin - Clears an area outside the border. The margin is transparent
• The box model allows us to add a border around elements, and to define space between
elements.
• Example
• Demonstration of the box model:
• div {
width: 300px;
border: 15px solid green;
padding: 50px;
margin: 20px;
}
• Width and Height of an Element
• In order to set the width and height of an element correctly in all
browsers, you need to know how the box model works.
• Example
• This <div> element will have a total width of 350px:
• div {
width: 320px;
padding: 10px;
border: 5px solid gray;
margin: 0;
}
CSS Text
• CSS has a lot of properties for formatting text.
• TEXT FORMATTING
• This text is styled with some of the text formatting properties. The heading
uses the text-align, text-transform, and color properties. The paragraph is
indented, aligned, and the space between characters is specified. The
underline is removed from this colored "Try it Yourself" link.
• Text Color
• The color property is used to set the color of the text. The color is
specified by:
• a color name - like "red"
• a HEX value - like "#ff0000"
• an RGB value - like "rgb(255,0,0)"
• Look at CSS Color Values for a complete list of possible color values.
• The default text color for a page is defined in the body selector.
• Example
• body {
color: blue;
}
h1 {
color: green;
}
• Text Color and Background Color
• In this example, we define both the background-color property and the color property:
• Example
• body {
background-color: lightgrey;
color: blue;
}
h1 {
background-color: black;
color: white;
}
div {
background-color: blue;
color: white;
}
• The CSS Text Color Property
• Property Description
• Color Specifies the color of text
CSS Text Alignment
• Text Alignment and Text Direction
• In this chapter you will learn about the following properties:
• text-align
• text-align-last
• direction
• unicode-bidi
• vertical-align
• Text Alignment
• The text-align property is used to set the horizontal alignment of a text.
• A text can be left or right aligned, centered, or justified.
• The following example shows center aligned, and left and right aligned text (left alignment is default if text
direction is left-to-right, and right alignment is default if text direction is right-to-left):
• Example
• h1 {
text-align: center;
}
h2 {
text-align: left;
}
h3 {
text-align: right;
}
• When the text-align property is set to "justify", each line is stretched so that every line has
equal width, and the left and right margins are straight (like in magazines and
newspapers):
• Example
• div {
text-align: justify;
}
• Text Align Last
• The text-align-last property specifies how to align the last line of a text.
• Example
• Align the last line of text in three <p> elements:
• p.a {
text-align-last: right;
}
p.b {
text-align-last: center;
}
p.c {
text-align-last: justify;
}
• Text Direction
• The direction and unicode-bidi properties can be used to change the text direction of an element:
• Example
• p{
direction: rtl;
unicode-bidi: bidi-override;
}
• Vertical Alignment
• The vertical-align property sets the vertical alignment of an element.
• Example
• Set the vertical alignment of an image in a text:
• img.a {
vertical-align: baseline;
}
img.b {
vertical-align: text-top;
}
img.c {
vertical-align: text-bottom;
}
img.d {
vertical-align: sub;
}
img.e {
vertical-align: super;
}
Advanced CSS layout
• Advanced CSS layout techniques are essential for creating complex and
responsive web designs. Here, I'll cover some advanced CSS layout
concepts and techniques that can help you create more flexible and
dynamic web layouts.
• Flexbox:
• Flexbox (Flexible Box Layout) is a powerful layout model that allows you to
design complex layouts with ease. You can create both horizontal and
vertical layouts using flex properties like display: flex, flex-direction, flex-
wrap, justify-content, and align-items. Flexbox is particularly useful for
creating navigation bars, card layouts, and centering elements.
• Example:
• .container {
• display: flex;
• justify-content: space-between;
• }
• Grid Layout: CSS Grid Layout is a two-dimensional layout system that's great for creating
grid-based designs. You can define rows and columns with the grid-template-rows and grid-
template-columns properties. Grid Layout excels at creating grid-based designs like
magazine layouts, image galleries, and responsive grids.
• Example:
• .grid-container {
• display: grid;
• grid-template-columns: 1fr 1fr 1fr;
• grid-gap: 20px;
• }
• CSS Grid and Flexbox Combo: Combining Flexbox and Grid Layout is a powerful technique
for creating advanced layouts. You can use Flexbox for the small-scale layout within grid
items and Grid Layout to structure the overall page layout. This combination allows for fine-
grained control over your design.
• CSS Variables (Custom Properties): CSS variables allow you to define reusable values in your
CSS, making it easier to maintain and update your layouts. You can use them for defining
colors, spacing, fonts, and more.
• Example:
• :root {
• --main-color: #3498db;
• }
• .button {
• background-color: var(--main-color);
• }
• Media Queries for Responsive Design: Media queries are essential for creating responsive layouts. They
allow you to apply different CSS styles based on the screen size or device. This technique ensures that
your website looks and functions well on various devices, from desktops to mobile phones.
• Example:
• @media screen and (max-width: 768px) {
• .navbar {
• display: none;
• }
• }
• Positioning: CSS positioning (position: relative, position: absolute, position: fixed) allows you to precisely
control the placement of elements within your layout. You can use it for creating overlays, sticky headers,
and tooltips.
• Example:
• .tooltip {
• position: absolute;
• top: -20px;
• left: 50%;
• transform: translateX(-50%);
• }
• CSS Grid Masonry Layout: To create a Pinterest-like masonry layout, you can use CSS Grid with a combination of grid-auto-
rows and column-count properties. This creates a dynamic, responsive grid where items flow into available space.
• Example:
• .masonry-grid {
• display: grid;
• grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
• grid-auto-rows: 10px;
• column-count: 3;
• grid-gap: 10px;
• }
• CSS Shapes: CSS Shapes allow you to create non-rectangular layouts and text wrapping around complex shapes. You can
use shape-outside, clip-path, and shape-margin properties for this purpose.
• Example:
• cssCopy code
• .shape { shape-outside: circle(50%); float: left; }
• Multi-Column Layout: CSS Multi-column layout is suitable for creating newspaper-style columns in your text content. You
can control the number of columns and the gap between them.
• Example:
• cssCopy code
• .multi-column-text { column-count: 3; column-gap: 20px; }
• Sticky Headers and Footers: You can create sticky headers and footers using the position: sticky property. This keeps certain
elements fixed at the top or bottom of the viewport as the user scrolls.
• Example:
• cssCopy code
• .header { position: sticky; top: 0; background-color: white; }
• These advanced CSS layout techniques, when combined and applied thoughtfully, enable you to create modern, responsive,
and visually appealing web designs. Remember that mastering CSS layout often involves experimentation and practice, so
don't hesitate to try out different approaches to achieve the desired results.
• .shape {
• shape-outside: circle(50%);
• float: left;
• }
• Multi-Column Layout: CSS Multi-column layout is suitable for creating newspaper-style
columns in your text content. You can control the number of columns and the gap between
them.
• Example:
• .multi-column-text {
• column-count: 3;
• column-gap: 20px;
• }
• Sticky Headers and Footers: You can create sticky headers and footers using the position:
sticky property. This keeps certain elements fixed at the top or bottom of the viewport as
the user scrolls.
• Example:
• .header {
• position: sticky;
• top: 0;
• background-color: white;
• }
Normal Flow
• Normal Flow:
• Normal flow is the default layout behavior of HTML
elements on a web page.
• In normal flow, elements are displayed one after
another vertically in the order they appear in the
HTML document, with each element taking up the
full width of its container.
• Elements flow from top to bottom and will wrap to
the next line if there isn't enough horizontal space.
Positioning Elements
• Positioning Elements:
• CSS provides various properties to control the positioning of elements on
a web page.
• The position property is commonly used for this purpose, and it can take
values like static, relative, absolute, fixed, and sticky.
• static is the default value and follows the normal flow.
• relative allows you to move an element relative to its normal position.
• absolute positions an element relative to its nearest positioned ancestor
(if any).
• fixed positions an element relative to the viewport, so it stays in the
same place even when you scroll.
• sticky is a hybrid of relative and fixed, as it's relative until it crosses a
certain threshold and then becomes fixed.
Floating Elements
• Floating Elements:
• The float property is used to control the positioning of an
element within its containing element, and it's often used
for creating layouts with multiple columns.
• Elements with float set to left or right are removed from
the normal flow and positioned to the left or right of their
containing element.
• Text and other inline elements will wrap around the floated
element.
• Common use cases include creating multi-column layouts
and floating images within text.
Constructing Multicolumn Layouts
• Creating multicolumn layouts in web design can be achieved using
CSS (Cascading Style Sheets). CSS provides several approaches to
create multicolumn layouts, depending on your design requirements
and browser compatibility considerations. Here are some common
approaches:
• Float-based Layout:
• This is one of the older methods but still widely used for
multicolumn layouts.
• Use the float property to make columns float next to each other
within a container.
• Clear the floats to ensure proper layout and avoid unexpected
behavior.
• Example:
• .column {
• float: left;
• width: 33.33%;
• }
• .clearfix::after {
• content: "";
• clear: both;
• display: table;
• }
• Flexbox:
• Flexbox is a more modern and flexible layout model for creating multicolumn layouts.
• It allows you to distribute space among items in a container, even when their sizes are unknown or dynamic.
• Example:
• .container {
• display: flex;
• }
• .column {
• flex: 1;
• }
• Grid Layout:
• CSS Grid Layout is a powerful layout system that enables you to create complex multicolumn layouts with
ease.
• Define a grid container and specify the number of columns and rows.
• Place items within the grid cells.
• Example:
• .container {
• display: grid;
• grid-template-columns: repeat(3, 1fr);
• grid-gap: 10px;
• }
• CSS Columns:
• The column-count and column-width properties allow you to create multicolumn layouts without
specifying exact column widths.
• Content is automatically flowed into columns based on the available space.
• Example:
• .container {
• column-count: 3;
• column-gap: 20px;
• }
• CSS Multi-Column Layout Module:
• The CSS Multi-Column Layout module provides more advanced control over multicolumn layouts.
• You can control column breaks, gaps, and column spans.
• Example
• .container {
• columns: 3;
• column-gap: 20px;
• column-fill: auto;
• }
Responsive Design:
– To make your multicolumn layouts responsive, use media
queries to adjust the layout based on screen size.
– You can change the number of columns or adjust column
widths for different screen sizes.
• Frameworks and Libraries:
– Consider using CSS frameworks like Bootstrap or CSS-in-JS
libraries like Styled-components to simplify multicolumn
layout creation and ensure cross-browser compatibility.
Approaches to CSS Layout
• Floats:
– The float property is used to push an element to one side of its containing element, allowing other content to
flow around it.
– Floats were historically used for creating multi-column layouts, but they have limitations and can be tricky to
work with for complex designs.
• CSS Flexbox:
– Flexbox is a one-dimensional layout model that allows you to distribute space along a single axis (either
horizontally or vertically).
– It simplifies the creation of responsive layouts and aligning elements within containers.
– It's well-suited for items in a single row or column.
• CSS Grid:
– CSS Grid is a two-dimensional layout system that enables you to create complex grid-based layouts.
– You can define both row and column layouts independently, making it highly flexible.
– It's particularly useful for creating grid-based designs, like magazine layouts or complex data tables.
• CSS Positioning:
• Positioning properties (e.g., position: relative/absolute/fixed) can be used to precisely control the
placement of elements on the page.
• Absolute positioning can be useful for layering elements, while relative positioning allows elements
to be positioned relative to their normal position in the document flow.
Responsive Design
• Responsive Design: Responsive design ensures that web pages adapt to
various screen sizes and devices. Key techniques for responsive design
include:
• Media Queries:
– Media queries allow you to apply different CSS styles based on the characteristics of the
user's device, such as screen width, height, or orientation.
– They are essential for creating responsive layouts that adjust content and design
according to the viewport size.
• Fluid Layouts:
– Use percentage-based widths and flexible containers to create layouts that expand or
contract based on screen size.
– Avoid fixed pixel values for layout components whenever possible.
• Mobile-First Design:
– Start designing your website for mobile devices first and then progressively enhance it
for larger screens using media queries.
– This approach ensures a better user experience on smaller screens.
CSS Frameworks
• The previous chapters have covered how to use CSS to make your page both stylish and responsive. While it is
certain possible to implement an entire site by creating your own CSS rules, that can quickly get tedious: often
you’d like a page to have a “standard” set of rules (because the browser’s style-less appearance) and then
customize those rules to your liking.
• For this reason, most professional web developers utilize an existing CSS Framework instead. A CSS Framework
is a stylesheet (a .css file!) that contains a large list of pre-defined rules that you can apply to your page. CSS
frameworks provide a number of benefits:
• Applies attractive default styling to all HTML elements: CSS frameworks make your pages instantly look better
through a bunch of element selector rules. Frameworks provide pleasant default fonts, line spacing, spacing,
and link styling without any extra effort on your part.
• Provides style classes for common UI components: framework stylesheets will also include CSS classes you can
add to your markup to easily include badges, in-page tabs, drop-down buttons, multi-column layouts, and more.
Frameworks enable you to add style your page by specifying CSS classes, rather than needing to define multiple
CSS rules for a single effect.
• CSS frameworks are thus designed to make your life easier and your development more efficient—while still
enabling you to provide your own customizations and styling with all of the power of CSS.
• There are many different CSS frameworks to choose from. Some popular ones include:
• Bootstrap is the most commonly used CSS framework on the web. Sometimes called “Twitter Bootstrap”, it was
originally created at Twitter to enforce some consistency among their internal tools, but was released as an
open-source project in 2011. Its popularity has benefits and drawbacks: it’s very well tested, documented, and
supported, but it’s also so prevalent that it’s default look has become cliché.
• As of this writing, the latest major version of Bootstrap is v5, released in May 2021. This is a major update of v4
(released in 2017). Note that Bootstrap 4 introduced Flexbox as a foundation for its grid system, offering better
performance. For this and other reasons, Bootstrap 4+ does not support IE 9 or earlier browsers. For older
browsers, you’d need to use an even earlier version—or probably just skip the framework entirely at that point.
• Foundation has a reputation for being more ahead-of-the-curve than Bootstrap (introducing
new features sooner). For example, it was the first framework to use a responsive mobile-
first design, and provided a Flexbox-based grid long before Bootstrap. Foundation has most
of the same UI elements as Bootstrap, but with a different look and feel (that can be
customized through a web-based tool).
• Material Components for the Web (MCW) is an official implementation of Google’s
Material Design visual language. This is the look-and-feel found in most Google products
and Android applications. Material Design is very opinionated so MCW is very difficult to
customize. The MCW style class names are also very verbose, as they follow the
Block, Element, Modifier (BEM) naming scheme.
• Materialize is the other popular Material Design implementation. This is an open-source
project, so it is not provided nor supported by Google. However, it is structurally similar to
Bootstrap, making it easy to learn and popular among people who know that framework.
• normalize.css is not so much a full framework as a small utility that performs browser
normalization (also called a “reset”). normalize.css standardizes the quirks across browsers
and making it so that the same HTML and CSS is displayed more consistently and without
errors. Note that most other frameworks include some version of this package (for example,
Bootstrap contains a fork called Reboot).
• If you choose not to use a framework, you should still include normalize to make your sites
consistent across browsers!
• Other frameworks exist as well, each with its own benefits and drawbacks (e.g., Skeleton is
designed to be as lightweight as possible, but at the cost of features).
• Using a Framework
• The important thing to realize is that a CSS framework is just a
stylesheet with a bunch of rules that someone else wrote for you.
There’s nothing magic about them. You can look at the stylesheet and
see all the rules that have been defined, and it’s all stuff you could
have written yourself (though some of it can be quite complex). But
those rules have been crafted by professionals and tested on a wide
array of browsers to ensure consistent results, so it’s a good idea to
build on top of them rather than trying to re-invent the wheel.
• For example, you can view the normalize.css file at
https://necolas.github.io/normalize.css/8.0.1/normalize.css and see
that it looks exactly like the CSS you might write on your own!
•
• Bootstrap
•
• This section discusses some of the features and uses
of the Bootstrap CSS framework. Note that many
other frameworks are used in a similar fashion
(though the specific classes and components may be
different).
• You include the Bootstrap framework by linking
its .css file to your page (whether from a CDN or a
local file). You can get the link for the latest version
from the Bootstrap Home Page.