Unit 2: Cascading Style Sheet

By Notes Vandar

2.1 How CSS fit with HTML page?

CSS (Cascading Style Sheets) is a language used to control the appearance and layout of HTML elements on a web page. It works alongside HTML to separate the structure of a web page (HTML) from its presentation (CSS). While HTML defines the content and structure, CSS defines how that content should look to the user.

There are three primary ways to integrate CSS with an HTML page: inline, internal, and external.


2.1.1 Inline CSS

Inline CSS is applied directly within an HTML element using the style attribute. This method is useful for applying styles to individual elements without affecting the rest of the page.

Example of Inline CSS:

<p style=”color: red; font-size: 20px;”>This is a red paragraph with inline CSS.</p>
  • Pros: Quick to apply for small changes.
  • Cons: Not efficient for managing large stylesheets, and hard to maintain.

2.1.2 Internal (Embedded) CSS

Internal CSS is defined within the <style> element in the <head> section of the HTML document. This method is used to apply styles to an entire page without affecting other pages.

Example of Internal CSS:

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Internal CSS Example</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
}
h1 {
color: blue;
}
p {
color: gray;
}
</style>
</head>
<body>
<h1>This is a heading with internal CSS</h1>
<p>This is a paragraph styled using internal CSS.</p>
</body>
</html>
  • Pros: Easier to manage styles for a single page.
  • Cons: Styles are only applied to one page, making it less efficient for larger websites with multiple pages.

2.1.3 External CSS

External CSS involves linking an external stylesheet (a separate .css file) to an HTML document using the <link> element in the <head> section. This is the most common and efficient way to apply CSS, especially for larger websites, as it allows you to control the styles of multiple pages with a single CSS file.

Example of External CSS:

HTML file (index.html):

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>External CSS Example</title>
<link rel=”stylesheet” href=”styles.css”>
</head>
<body>
<h1>This is a heading with external CSS</h1>
<p>This is a paragraph styled using external CSS.</p>
</body>
</html>

CSS file (styles.css):

body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
}

h1 {
color: blue;
}

p {
color: gray;
}

  • Pros: Centralized control of styles across multiple pages, easier to maintain and update.
  • Cons: Requires an extra HTTP request to load the external CSS file (though this can be cached by the browser).

2.1.4 CSS Selectors and Properties

CSS works by selecting HTML elements and applying styles to them. The selection is done using CSS selectors (such as tags, classes, or IDs), and the styling is defined using CSS properties.

Example:

/* Select all <p> elements */
p {
color: blue; /* Sets text color to blue */
font-size: 16px; /* Sets font size */
}

/* Select element with class=”highlight” */
.highlight {
background-color: yellow; /* Sets background color */
}

/* Select element with id=”main-title” */
#main-title {
text-align: center; /* Aligns text to the center */
}


2.1.5 The Cascade and Specificity

CSS follows a cascading rule, meaning that if multiple styles are applied to the same element, the most specific rule will take precedence. Specificity is determined by the type of selector:

  • Element selector (h1, p) has the lowest specificity.
  • Class selector (.class) has medium specificity.
  • ID selector (#id) has the highest specificity.

In case of conflicting styles, the more specific rule will win.


2.1.6 Benefits of Using CSS with HTML

  1. Separation of concerns: HTML is responsible for the structure/content, while CSS is responsible for the design/layout.
  2. Consistency: External CSS can be reused across multiple web pages, ensuring a consistent design.
  3. Maintenance: It is easier to update the style of multiple pages by editing a single CSS file.
  4. User Experience: CSS allows for responsive designs, which can adapt to different screen sizes and devices, improving the user experience.
  5. Performance: CSS files can be cached by browsers, reducing page load times.

2.2 Inline, Internal and External CSS

When using CSS to style HTML elements, there are three primary ways to apply CSS: inline, internal, and external. Each method serves different purposes and has its own advantages and disadvantages.


2.2.1 Inline CSS

Inline CSS involves adding styles directly to the HTML elements using the style attribute. This method is useful for quickly applying styles to a specific element without affecting the rest of the page.

Example of Inline CSS:

<p style=”color: red; font-size: 18px;”>This is an inline styled paragraph.</p>

In this example, the paragraph will have red text and a font size of 18 pixels.

Advantages:

  • Quick to apply for individual elements.
  • Useful for applying unique styles that only affect a single element.

Disadvantages:

  • Difficult to maintain, especially for large projects.
  • Inline CSS mixes content (HTML) and presentation (CSS), violating the principle of separation of concerns.
  • It cannot be reused across multiple elements or pages.

2.2.2 Internal (Embedded) CSS

Internal CSS is applied using a <style> tag inside the <head> section of an HTML document. This allows you to define styles for the entire page within the same HTML file.

Example of Internal CSS:

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Internal CSS Example</title>
<style>
body {
background-color: lightblue;
}
h1 {
color: navy;
text-align: center;
}
p {
font-size: 16px;
color: darkgray;
}
</style>
</head>
<body>
<h1>Internal CSS Example</h1>
<p>This paragraph is styled using internal CSS.</p>
</body>
</html>

In this example, all elements inside the <style> block will be styled according to the rules defined there.

Advantages:

  • Styles are easy to maintain for a single web page.
  • You can apply styles to multiple elements within the same page.

Disadvantages:

  • Styles only apply to the page where the internal CSS is written.
  • It can clutter the HTML file if there are many styles, making the document harder to manage.
  • Not efficient for large-scale websites where consistent styling is needed across multiple pages.

2.2.3 External CSS

External CSS is written in a separate file (with the .css extension) and linked to the HTML document using the <link> tag. This is the most efficient and scalable way to apply CSS, especially for larger projects.

Example of External CSS:

HTML file (index.html):

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>External CSS Example</title>
<link rel=”stylesheet” href=”styles.css”>
</head>
<body>
<h1>External CSS Example</h1>
<p>This paragraph is styled using external CSS.</p>
</body>
</html>

CSS file (styles.css):

body {
background-color: lightgray;
}

h1 {
color: green;
text-align: center;
}

p {
font-size: 14px;
color: black;
}

Here, the styles.css file contains all the CSS rules, and the <link> tag in the HTML file connects this external stylesheet to the HTML page.

Advantages:

  • Allows for separation of concerns: content (HTML) is separated from presentation (CSS).
  • Efficient for managing and updating styles across multiple pages.
  • The CSS file can be cached by the browser, improving load times.
  • Easy to maintain and scale for larger projects.

Disadvantages:

  • Requires an extra HTTP request to load the CSS file (though this is often cached).
  • Not suitable for one-off, specific styles for individual elements on a single page.

2.2.4 Comparison of Inline, Internal, and External CSS

Feature Inline CSS Internal CSS External CSS
Where it’s written Inside the style attribute of an element. Inside a <style> tag in the <head>. In a separate .css file linked to HTML.
Scope Affects a single element. Affects the entire page. Affects all pages linked to the CSS file.
Reusability Not reusable. Reusable within the page. Highly reusable across multiple pages.
Maintenance Difficult to maintain for large sites. Easier for single-page sites. Easiest for large sites.
Performance Minimal performance impact. Minimal impact unless overused. May slow down initial page load (cached).
Best Use Case Small changes or overrides. When styling is needed for one page only. Large websites with consistent styling.

When to Use Each CSS Method

  • Inline CSS: Use when you need to apply a unique style to a single element, and performance isn’t a concern. It’s ideal for one-time, quick changes.
  • Internal CSS: Use when you want to style a single HTML document and don’t expect to reuse the styles in other pages. It can be helpful for testing or styling standalone pages.
  • External CSS: Use when you have multiple HTML pages and want to apply a consistent style across the website. It’s the most scalable, maintainable, and efficient approach for large projects

 

2.3 CSS Selectors

CSS selectors are patterns used to select and target HTML elements for styling. They allow you to apply specific styles to elements or groups of elements based on their tag names, classes, IDs, attributes, and more.

Selectors are the foundation of CSS because they determine which HTML elements the CSS rules apply to.


2.3.1 Basic Selectors

1. Universal Selector (*)

The universal selector selects all elements in an HTML document.

* {
margin: 0;
padding: 0;
}

In this example, all elements will have their margin and padding set to 0.


2. Type Selector (Element Selector)

The type selector selects all instances of a specific HTML tag (element). For example, to select all <p> elements:

p {
font-size: 16px;
color: blue;
}

This applies a font size of 16 pixels and blue color to all paragraphs (<p>).


3. Class Selector (.class)

The class selector targets elements with a specific class attribute. Classes are reusable, meaning multiple elements can share the same class.

.text-large {
font-size: 20px;
color: green;
}

HTML:

<p class=”text-large”>This paragraph will have larger text.</p>
<div class=”text-large”>This div will also have larger text.</div>

In this example, both the paragraph and the div with the text-large class will be styled with a font size of 20 pixels and green color.


4. ID Selector (#id)

The ID selector targets an element with a specific id attribute. Unlike classes, IDs must be unique within an HTML document.

#main-heading {
font-size: 30px;
color: red;
}

HTML:

<h1 id=”main-heading”>Main Heading</h1>

This example applies styles to the element with the ID main-heading.


2.3.2 Grouping Selectors

h1, h2, h3 {
font-family: Arial, sans-serif;
color: navy;
}

In this example, all <h1>, <h2>, and <h3> elements will have the same font family and color.


2.3.3 Descendant Selector (Space )

The descendant selector targets elements that are nested (descendants) inside a specific element.

div p {
color: purple;
}

HTML:

<div>
<p>This paragraph is inside a div and will be purple.</p>
</div>
<p>This paragraph is not inside a div and will not be purple.</p>
In this case, only the paragraph inside the <div> will have purple text.

2.3.4 Child Selector (>)

The child selector targets elements that are direct children of a specific parent element.

ul > li {
font-size: 18px;
}

HTML:

<ul>
<li>Direct child list item</li>
<li>Another direct child list item</li>
</ul>

This targets only the direct child <li> elements of the <ul> (unordered list).


2.3.5 Sibling Selectors

  • Adjacent Sibling Selector (+): Targets the next sibling element that immediately follows a specific element.
h1 + p {
color: gray;
}

HTML:

<h1>Heading</h1>
<p>This paragraph immediately follows the heading.</p>
<p>This paragraph will not be selected.</p>
  • General Sibling Selector (~): Selects all sibling elements after a specific element.
h1 ~ p {
color: orange;
}

HTML:

<h1>Heading</h1>
<p>This paragraph follows the heading.</p>
<p>All paragraphs after the heading will be styled.</p>

2.3.6 Attribute Selector

Attribute selectors allow you to target elements based on the presence or value of an attribute.

  • [attribute]: Selects elements with the specified attribute.
input[type=”text”] {
border: 1px solid blue;
}

HTML:

<input type=”text” name=”username”>
<input type=”password” name=”password”>

In this example, only the text input field will have a blue border.


2.3.7 Pseudo-classes

Pseudo-classes are used to define a special state of an element, such as when a user hovers over it or when a link has been visited.

  • :hover: Styles an element when the user hovers over it.
button:hover {
background-color: lightblue;
}
  • :nth-child(n): Targets an element based on its position in its parent.
li:nth-child(2) {
color: red;
}

This will make the second <li> in an unordered list red.


2.3.8 Pseudo-elements

Pseudo-elements allow you to style specific parts of an element, such as the first line of a paragraph or the first letter.

  • ::first-line: Styles the first line of a block of text.
p::first-line {
font-weight: bold;
}
  • ::before and ::after: Inserts generated content before or after an element.
h1::before {
content: “★ “;
}

2.4 CSS Properties for Text, List, Table, Background, and Link Formatting

CSS provides a wide range of properties to control the appearance and formatting of different HTML elements. Below are some commonly used CSS properties categorized by their use for text, lists, tables, backgrounds, and links.


2.4.1 CSS Properties for Text Formatting

1. color: Sets the color of the text.

p {
color: blue;
}

2. font-family: Specifies the font of the text.

p {
font-family: Arial, sans-serif;
}

3. font-size: Sets the size of the font.

h1 {
font-size: 24px;
}

4. font-weight: Controls the boldness of the text.

strong {
font-weight: bold;
}

5. text-align: Aligns the text horizontally.

p {
text-align: center;
}

6. text-decoration: Adds or removes decoration (such as underlining) to text.

a {
text-decoration: none;
}

7. line-height: Specifies the height of the lines of text (useful for controlling spacing between lines).

p {
line-height: 1.5;
}

8. letter-spacing: Adjusts the spacing between characters.

h1 {
letter-spacing: 2px;
}

9. text-transform: Changes the case of the text.

h2 {
text-transform: uppercase;
}

10. text-shadow: Adds shadow to the text.

h1 {
text-shadow: 2px 2px 5px gray;
}

2.4.2 CSS Properties for Lists

1. list-style-type: Defines the marker style for list items (e.g., bullets, numbers).

ul {
list-style-type: square;
}
ol {
list-style-type: decimal;
}

2. list-style-position: Specifies whether the bullet or number appears inside or outside the list item.

ul {
list-style-position: inside;
}

3. list-style-image: Replaces the list marker with an image.

ul {
list-style-image: url(‘bullet.png’);
}

4. list-style: A shorthand property for setting all list properties at once.

ul {
list-style: square inside;
}

2.4.3 CSS Properties for Tables

1. border-collapse: Specifies whether table borders should collapse into a single border or remain separate.

table {
border-collapse: collapse;
}

2. border-spacing: Sets the space between the borders of adjacent cells.

table {
border-spacing: 10px;
}

3. table-layout: Defines the layout algorithm for table cells.

table {
table-layout: fixed;
}

4. text-align and vertical-align: Aligns the content inside the table cells.

th {
text-align: left;
vertical-align: middle;
}

5. width and height: Sets the width and height of table cells.

td {
width: 150px;
height: 50px;
}

6. padding: Adds padding inside the table cells.

td {
padding: 10px;
}

7. border: Adds borders around table elements.

table, th, td {
border: 1px solid black;
}

2.4.4 CSS Properties for Background Formatting

1. background-color: Sets the background color of an element.

body {
background-color: lightblue;
}

2. background-image: Adds an image as the background of an element.

body {
background-image: url(‘background.jpg’);
}

3. background-position: Specifies the position of the background image.

body {
background-position: center;
}

4. background-repeat: Controls whether the background image repeats, and how.

body {
background-repeat: no-repeat;
}

5. background-size: Defines the size of the background image.

body {
background-size: cover;
}

6. background-attachment: Determines whether the background image scrolls with the content or remains fixed.

body {
background-attachment: fixed;
}

7. background: A shorthand property for setting all background properties in one declaration.

body {
background: lightblue url(‘background.jpg’) no-repeat center fixed;
}

2.4.5 CSS Properties for Link Formatting

1. color: Specifies the color of the link.

cssa {
color: blue;
}

2. text-decoration: Adds or removes underlining or other decoration from links.

a {
text-decoration: none;
}

3. :hover: Defines styles when the user hovers over a link.

a:hover {
color: red;
text-decoration: underline;
}

4. :visited: Styles links that the user has already visited.

a:visited {
color: purple;
}

5. :active: Styles the link when it is being clicked or activated.

a:active {
color: green;
}

2.5 Pseudo classes: before, after, first-line, first-letter, hover, focus, active

Pseudo-classes and pseudo-elements allow you to apply styles to elements based on their state or specific parts of an element. These are useful for interactive designs and for targeting elements more precisely.


2.5.1 ::before and ::after (Pseudo-elements)

  • ::before: Used to insert content before an element.
  • ::after: Used to insert content after an element.

These pseudo-elements are often used for adding visual elements or decorative content to an element, such as icons, quotations, or styling effects.

Example:

h1::before {
content: ” “; /* Adds a star before the heading */
}

h1::after {
content: ” “; /* Adds a star after the heading */
}

HTML:

<h1>Heading with Stars</h1>
This will render: Heading with Stars

You can use ::before and ::after to insert content like symbols, icons, or custom styling.


2.5.2 ::first-line (Pseudo-element)

The ::first-line pseudo-element allows you to style the first line of a block of text separately from the rest of the text. This is useful for creating typographic effects like highlighted or bolded first lines.

Example:

p::first-line {
font-weight: bold;
font-size: 18px;
}

HTML:

<p>This is the first paragraph, and the first line of this text will be bold and larger than the rest of the text.</p>

In this example, the first line of the paragraph will appear bold and larger, while the rest of the text will retain the default style.


2.5.3 ::first-letter (Pseudo-element)

The ::first-letter pseudo-element is used to style the first letter of a block of text. It is often used in articles or design to create “drop caps.”

Example:

p::first-letter {
font-size: 32px;
font-weight: bold;
color: red;
float: left;
margin-right: 5px;
}

HTML:

<p>This is the first paragraph, and the first line of this text will be bold and larger than the rest of the text.</p>

This will style the first letter of the paragraph, making it larger, bold, and red, often creating a decorative effect at the start of a paragraph.


2.5.4 :hover (Pseudo-class)

The :hover pseudo-class applies styles to an element when the user hovers over it with the mouse. This is often used for interactive elements like buttons or links.

Example:

button:hover {
background-color: lightblue;
cursor: pointer;
}

HTML:

<button>Hover me</button>

When the user hovers over the button, the background color will change to light blue.


2.5.5 :focus (Pseudo-class)

The :focus pseudo-class applies styles when an element receives focus, such as when a user clicks inside an input field or navigates to an element using the keyboard (e.g., pressing “Tab”).

Example:

input:focus {
border: 2px solid green;
outline: none;
}

HTML:

<input type=”text” placeholder=”Focus me!”>

When the input field is clicked or focused, its border will change to green, and the default outline will be removed.


2.5.6 :active (Pseudo-class)

The :active pseudo-class applies styles to an element when it is being activated, such as when a button or link is being clicked. This style remains active while the user is holding the mouse button down.

Example:

a:active {
color: red;
}

HTML:

<a href=”#”>Click me</a>

When the link is clicked, the text color will change to red while the user is holding down the mouse button

 

2.6 Custom list numbering using content property

The CSS content property, used with ::before and ::after pseudo-elements, allows for custom numbering and styling in lists. This method gives you complete control over how the list numbers or markers are displayed, rather than using the default browser-provided list styles.

Here’s how to create custom list numbering using the content property.


2.6.1 Steps for Custom List Numbering

  1. Remove default list style: The default list styling (numbers or bullets) should be removed by setting the list-style-type to none.
  2. Use ::before pseudo-element: You will use the ::before pseudo-element on each list item (li) to insert the custom number or marker.
  3. Use counter-reset and counter-increment: These properties manage custom counters for the list. counter-reset initializes the counter, and counter-increment increases the counter for each list item.

Example: Custom List with Numbers

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<style>
/* Initialize the counter */
ol.custom-counter {
counter-reset: custom-counter; /* Starts at 0 */
list-style-type: none; /* Removes default numbering */
padding-left: 0;
}

/* Style the list items */
ol.custom-counter li {
counter-increment: custom-counter; /* Increment counter for each li */
margin-bottom: 10px;
}

/* Insert custom number before each list item */
ol.custom-counter li::before {
content: counter(custom-counter) “. “; /* Custom numbering */
font-weight: bold;
color: blue;
margin-right: 10px;
}
</style>
<title>Custom List Numbering</title>
</head>
<body>

<ol class=”custom-counter”>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
<li>Fourth item</li>
</ol>

</body>
</html>

Explanation:

  • counter-reset: custom-counter;: Initializes a custom counter named custom-counter.
  • counter-increment: custom-counter;: Increments the custom counter for each list item (li).
  • content: counter(custom-counter) ". ";: Uses the counter value and appends a period (. ) to it for custom numbering.

This will display the following:

  1. First item
  2. Second item
  3. Third item
  4. Fourth item

2.6.2 Example: Custom List with Roman Numerals

You can use different numbering systems (such as Roman numerals or letters) with the list-style and counter() function.

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<style>
/* Initialize the counter */
ol.roman-counter {
counter-reset: roman-counter;
list-style-type: none;
padding-left: 0;
}

/* Style list items and increment the counter */
ol.roman-counter li {
counter-increment: roman-counter;
margin-bottom: 10px;
}

/* Insert Roman numerals before each list item */
ol.roman-counter li::before {
content: counter(roman-counter, upper-roman) “. “;
font-weight: bold;
color: maroon;
margin-right: 10px;
}
</style>
<title>Custom Roman Numeral List</title>
</head>
<body>

<ol class=”roman-counter”>
<li>Introduction</li>
<li>Background</li>
<li>Methodology</li>
<li>Conclusion</li>
</ol>

</body>
</html>

In this example, the list will be numbered in uppercase Roman numerals:

I. Introduction
II. Background
III. Methodology
IV. Conclusion


2.6.3 Custom List with Letters (Uppercase/Lowercase)

/* Uppercase Letters */
ol.upper-alpha {
counter-reset: upper-alpha;
list-style-type: none;
}

ol.upper-alpha li {
counter-increment: upper-alpha;
}

ol.upper-alpha li::before {
content: counter(upper-alpha, upper-alpha) “. “;
font-weight: bold;
}

/* Lowercase Letters */
ol.lower-alpha {
counter-reset: lower-alpha;
list-style-type: none;
}

ol.lower-alpha li {
counter-increment: lower-alpha;
}

ol.lower-alpha li::before {
content: counter(lower-alpha, lower-alpha) “. “;
font-weight: bold;
}

  • For uppercase letters, the upper-alpha counter is used.
  • For lowercase letters, the lower-alpha counter is used.

 

2.7 CSS Box Model: margin, padding and border

The CSS box model is a fundamental concept that defines how elements are structured and displayed on a web page. Every element in HTML is represented as a rectangular box, and the box model consists of four parts: content, padding, border, and margin.

Here’s a breakdown of the CSS box model structure:

+——————————-+
| Margin |
+——————————-+
| Border |
+——————————-+
| Padding |
+——————————-+
| Content |
+——————————-+
  • Content: The actual content of the element, like text or images.
  • Padding: Space between the content and the element’s border.
  • Border: The boundary around the padding (optional, can be styled).
  • Margin: Space outside the border, separating the element from other elements.

2.7.1 Padding

The padding property defines the space between the content of the element and its border. It expands the space inside the border, making the content appear further away from the edges.

Example:

div {
padding: 20px; /* Adds 20px space inside the element */
}

HTML:

<div>This is some content inside a box with padding.</div>
  • You can also specify individual padding for each side:
    • padding-top
    • padding-right
    • padding-bottom
    • padding-left

Example:

div {
padding: 10px 20px 15px 5px; /* top, right, bottom, left */
}

This will apply different padding values to each side of the element.


2.7.2 Border

The border property is the area between the padding and the margin, which defines the visual boundary of an element. It can be styled in various ways (solid, dotted, dashed, etc.), colored, and given thickness.

Example:

div {
border: 2px solid black; /* 2px thick solid black border */
}

HTML:

<div>This box has a 2px solid border.</div>

You can also specify individual borders for each side:

  • border-top
  • border-right
  • border-bottom
  • border-left

Example:

div {
border-bottom: 3px dashed red; /* Adds a dashed red bottom border */
}

In addition to style and color, the border-radius property can be used to create rounded corners.

Example:

div {
border: 2px solid black;
border-radius: 10px; /* Rounded corners */
}

2.7.3 Margin

The margin property defines the space outside the border, separating the element from neighboring elements. Unlike padding, margins affect the distance between elements.

Example:

div {
margin: 20px; /* Adds 20px space outside the element */
}

HTML:

<div>This box has a margin of 20px.</div>
  • Similar to padding, you can also specify different margins for each side:
    • margin-top
    • margin-right
    • margin-bottom
    • margin-left

Example:

div {
margin: 10px 15px 20px 5px; /* top, right, bottom, left */
}

You can also set the margin to auto for centering an element horizontally:

div {
width: 50%;
margin: 0 auto; /* Centers the div horizontally */
}

Example: Combining Margin, Padding, and Border

div {
width: 200px;
padding: 20px;
border: 3px solid green;
margin: 30px;
}

HTML:

<div>This box demonstrates padding, border, and margin.</div>
  • The width of the element is set to 200px.
  • The padding of 20px will be added inside the border.
  • The border is 3px thick and solid green.
  • The margin creates 30px of space between this element and any surrounding elements.

2.7.4 Box Model Formula

The box model affects the total width and height of an element. The formula for calculating the total width and height is:

  • Total Width = Content Width + Padding (left + right) + Border (left + right) + Margin (left + right)
  • Total Height = Content Height + Padding (top + bottom) + Border (top + bottom) + Margin (top + bottom)

Example:

If an element has the following properties:

div {
width: 300px;
padding: 20px;
border: 10px solid black;
margin: 15px;
}

The total width will be:

Total Width = 300px (content) + 20px (padding-left) + 20px (padding-right)
+ 10px (border-left) + 10px (border-right)
+ 15px (margin-left) + 15px (margin-right)
= 390px

So, the total width of the element is 390px, even though the content width is set to 300px.

 

2.8 Creating Layouts with display, position and float property

In CSS, layouts determine how elements are arranged on a web page. The properties display, position, and float are essential for creating layouts. These properties control how elements behave, are positioned, and interact with other elements.


2.8.1 The display Property

The display property determines how an element is rendered on the page. It can define whether an element is a block-level element, an inline element, or something else (like flex or grid). Some common values of display include:

  1. display: block;
    • Block elements take up the full width available and start on a new line. Examples: <div>, <p>, <h1>.
    • Example:
      div {
      display: block;
      background-color: lightgray;
      width: 100%;
      }
  2. display: inline;
    • Inline elements take up only as much width as needed and do not start on a new line. Examples: <span>, <a>.
    • Example:
      span {
      display: inline;
      background-color: yellow;
      }
  3. display: inline-block;
    • Inline-block elements behave like inline elements but respect height and width properties like block elements.
    • Example:
      div {
      display: inline-block;
      width: 150px;
      height: 100px;
      background-color: lightblue;
      }
  4. display: none;
    • Hides the element entirely. It is not visible on the page and doesn’t occupy any space.
    • Example:
      p.hidden {
      display: none;
      }
  5. display: flex;
    • Flexbox layouts allow flexible alignment and distribution of elements in a container.
    • Example:
      .container {
      display: flex;
      justify-content: space-between;
      }
  6. display: grid;
    • CSS Grid layouts are used to create grid-based designs.
    • Example:
      .container {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      }

2.8.2 The position Property

The position property controls how an element is positioned in relation to its containing element or the document. There are several values:

  1. position: static; (default)
    • The element is positioned according to the normal document flow (no special positioning).
  2. position: relative;
    • Positioned relative to its normal position. You can use top, left, right, and bottom properties to adjust the element’s final position relative to where it would normally be.
    • Example:
      .box {
      position: relative;
      top: 10px;
      left: 20px;
      }
  3. position: absolute;
    • Positioned relative to the nearest positioned ancestor (non-static), or relative to the document if no such ancestor exists. It is removed from the normal flow.
    • Example:
      .box {
      position: absolute;
      top: 50px;
      left: 100px;
      }
  4. position: fixed;
    • Positioned relative to the viewport, meaning it stays fixed in the same place even if the page is scrolled.
    • Example:
      .fixed-header {
      position: fixed;
      top: 0;
      width: 100%;
      background-color: black;
      color: white;
      }
  5. position: sticky;
    • A hybrid of relative and fixed positioning. The element remains in the normal flow but “sticks” to a given position when you scroll past it.
    • Example:
      .sticky-header {
      position: sticky;
      top: 0;
      }

2.8.3 The float Property

The float property allows elements to be aligned to the left or right of their container, with text and inline elements flowing around them. It’s often used for creating basic layouts, but has largely been replaced by Flexbox and Grid in modern design.

  • float: left;: Floats the element to the left of its container, allowing content to wrap around it.
  • float: right;: Floats the element to the right.
  • clear: both;: Clears the float, preventing elements from wrapping around.

Example: Floating an Image with Text Wrap:

img {
float: left;
margin-right: 20px; /* Adds space between image and text */
}

p {
clear: both; /* Ensures the paragraph starts after the floated elements */
}

HTML:

<img src=”image.jpg” alt=”Image” width=”200″>
<p>This paragraph wraps around the image. The image is floated to the left, so text flows naturally on the right.</p>

The image will float to the left and the paragraph text will wrap around it.


2.8.4 Example: Basic Layout Using display, position, and float

Let’s create a basic page layout using display, position, and float.

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<style>
/* Container styles */
.container {
width: 100%;
display: flex; /* Flexbox layout */
justify-content: space-between;
}

/* Header */
header {
background-color: lightgray;
padding: 20px;
position: sticky;
top: 0;
}

/* Sidebar */
.sidebar {
width: 20%;
float: left; /* Floats sidebar to the left */
background-color: lightblue;
padding: 20px;
}

/* Main content */
.content {
width: 75%;
float: right;
background-color: lightgreen;
padding: 20px;
}

/* Footer */
footer {
clear: both; /* Clears float */
background-color: gray;
padding: 20px;
text-align: center;
}
</style>
<title>Basic Layout</title>
</head>
<body>

<header>
<h1>Website Header</h1>
</header>

<div class=”container”>
<div class=”sidebar”>
<h2>Sidebar</h2>
<p>This is the sidebar content.</p>
</div>

<div class=”content”>
<h2>Main Content</h2>
<p>This is the main content section. The layout is created using float and flexbox for layout management.</p>
</div>
</div>

<footer>
<p>Footer Content</p>
</footer>

</body>
</html>

Breakdown of the Layout:

  1. Header: Positioned as sticky, it stays at the top of the page when the user scrolls.
  2. Sidebar: Floated to the left, taking up 20% of the container’s width.
  3. Main Content: Floated to the right, taking up 75% of the container’s width.
  4. Footer: Uses clear: both to prevent it from wrapping around floated elements.

2.9 Fixed and Liquid design of the page

Web design can be categorized into two main layout strategies: fixed design and liquid design. Each approach has its strengths and is suitable for different use cases, depending on the desired behavior of the page when displayed on various screen sizes or devices.


2.9.1 Fixed Design

In fixed design, the width of the web page and its elements are set using fixed measurements (usually pixels). Regardless of the screen size or resolution, the elements retain their specific dimensions, which can cause the design to look the same on all devices, but may result in horizontal scrolling on smaller screens or large empty spaces on larger screens.

Characteristics of Fixed Design:

  1. Width in pixels: The width of the layout is specified in pixels (px), meaning it remains constant regardless of the screen size.
  2. Consistency: The layout will look the same across all devices with no changes in the size of elements.
  3. Centered Layout: Often, the layout is centered within the viewport (browser window), with equal margins on both sides.

Example of Fixed Design:

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”FacultyUTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<style>
body {
margin: 0;
padding: 0;
}

.container {
width: 960px; /* Fixed width of 960px */
margin: 0 auto; /* Center the container */
background-color: lightgray;
}

header, footer {
background-color: darkgray;
padding: 20px;
text-align: center;
}

.content {
padding: 20px;
}
</style>
<title>Fixed Design</title>
</head>
<body>

<div class=”container”>
<header>
<h1>Fixed Width Layout</h1>
</header>

<div class=”content”>
<p>This is a fixed width layout. The content is set to 960px wide, and it does not change based on the screen size.</p>
</div>

<footer>
<p>Footer Content</p>
</footer>
</div>

</body>
</html>

In the above example:

  • The .container has a fixed width of 960px, ensuring the layout looks the same on all devices.
  • On smaller screens, the content may require horizontal scrolling.
  • On larger screens, there will be extra white space on either side of the container.

Pros of Fixed Design:

  • Control: Designers have complete control over the layout and appearance of the page.
  • Consistency: The design remains consistent across different screen sizes, making it easier to maintain a specific look.

Cons of Fixed Design:

  • Not responsive: On smaller devices, the fixed layout might result in a poor user experience due to horizontal scrolling.
  • Wasted space on large screens: On wider screens, a lot of unused white space may appear on the sides.

2.9.2 Liquid (Fluid) Design

In liquid design (also known as fluid design), the width of the page and elements are defined in relative units, such as percentages (%). This approach allows the page to stretch or shrink based on the screen size, ensuring that the layout adapts to different devices and resolutions without requiring horizontal scrolling.

Characteristics of Liquid Design:

  1. Width in percentages: Instead of using fixed widths, the width of elements is defined in percentages, which makes the layout flexible and responsive to the browser window.
  2. Dynamic resizing: As the viewport size changes (e.g., resizing the browser window or viewing on different devices), the content adjusts to fit the available space.
  3. Responsive layout: Liquid designs are more fluid and responsive, providing a better experience on different screen sizes.

Example of Liquid Design:

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<style>
body {
margin: 0;
padding: 0;
}

.container {
width: 80%; /* Liquid width based on percentage */
margin: 0 auto; /* Center the container */
background-color: lightblue;
}

header, footer {
background-color: darkblue;
padding: 20px;
text-align: center;
color: white;
}

.content {
padding: 20px;
}
</style>
<title>Liquid Design</title>
</head>
<body>

<div class=”container”>
<header>
<h1>Liquid Width Layout</h1>
</header>

<div class=”content”>
<p>This is a liquid width layout. The content width adjusts based on the screen size, making the layout more flexible and responsive.</p>
</div>

<footer>
<p>Footer Content</p>
</footer>
</div>

</body>
</html>


Important Questions
Comments
Discussion
0 Comments
  Loading . . .