π Lecture 23 β HTML Head
π Overview: This lecture covers the HTML
<head>element and its role in storing metadata about web documents. It explains how to properly structure document metadata including title, styles, scripts, and character encoding, and introduces HTML entities, symbols, character encoding standards, and URL encoding for proper web page functionality.
ποΈ Topics Covered
The lecture covers the HTML <head> element and its child elements including <title>, <style>, <link>, <meta>, <script>, and <base>. It also explains how to omit <html>, <body>, and <head> tags in HTML5. Additional topics include HTML entities and non-breaking spaces, combining diacritical marks, HTML symbol entities (mathematical symbols and Greek letters), character encoding standards (ASCII, ANSI, ISO-8859-1, UTF-8), and URL structure with encoding rules.
π Lecture Summary
The HTML <head> Element
The <head> element is a container for Metadata (data about data). HTML metadata is data about the HTML document and is not displayed. Metadata typically defines document title, styles, links, scripts, and other meta information. The following tags describe metadata: <title>, <style>, <meta>, <link>, <script>, and <base>.
π Definition β Metadata: Data about the HTML document that is not displayed but defines document properties like title, styles, and scripts.
Omitting <html> and <body>
In the HTML5 standard, the <html>, <body>, and <head> tags can be omitted. The <html> element is the document root and is the recommended place for specifying the page language using the lang attribute:
<!DOCTYPE html>
<html lang="en-US">
Declaring a language is important for accessibility applications (screen readers) and search engines. Omitting <html> and <body> can crash badly written DOM and XML software. Omitting <body> can produce errors in older browsers (IE9).
Omitting <head>
In HTML5, the <head> tag can also be omitted. By default, browsers will add all elements before <body> to a default <head> element. You can reduce the complexity of HTML by omitting the <head> tag.
The HTML <title> Element
The <title> element defines the title of the document and is required in all HTML/XHTML documents. The <title> element:
- Defines a title in the browser toolbar
- Provides a title for the page when it is added to favorites
- Displays a title for the page in search engine results
The HTML <style> Element
The <style> element is used to define style information for an HTML document. Inside the <style> element you specify how HTML elements should render in a browser:
<style>
body {background-color:yellow;}
p {color:blue;}
</style>
The HTML <link> Element
The <link> element defines the page relationship to an external resource. It is most often used to link to style sheets:
<link rel="stylesheet" href="mystyle.css">
<meta> Element
The <meta> element is used to specify page description, keywords, author, and other metadata. Metadata is used by browsers (how to display content), by search engines (keywords), and other web services.
Define keywords for search engines:
<meta name="keywords" content="HTML, CSS, XML, XHTML, JavaScript">
Define a description of your web page:
<meta name="description" content="Free Web tutorials on HTML and CSS">
Define the character set:
<meta charset="UTF-8">
Define the author of a page:
<meta name="author" content="Hege Refsnes">
Refresh document every 30 seconds:
<meta http-equiv="refresh" content="30">
The HTML <script> Element
The <script> element is used to define client-side JavaScripts. Example:
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello JavaScript!";
}
</script>
The HTML <base> Element
The <base> element specifies the base URL and base target for all relative URLs in a page:
<base href="http://www.google.com/images/" target="_blank">
HTML Entities
Some characters are reserved in HTML. If you use the less than (<) or greater than (>) signs in your text, the browser might mix them with tags. Character entities are used to display reserved characters in HTML. A character entity looks like this:
&entity_name;
OR
&#entity_number;
To display a less than (<) sign we must write: < or <
π Definition β Character entities: Codes used to display reserved characters in HTML that might otherwise be interpreted as HTML tags.
Non Breaking Space
A common character entity used in HTML is the non breaking space ( ). Browsers will always truncate spaces in HTML pages. If you write 10 spaces in your text, the browser will remove 9 of them. To add real spaces to your text, you can use the character entity.
Combining Diacritical Marks
A diacritical mark is a "glyph" added to a letter. Some diacritical marks, like grave (`) and acute (Β΄) are called accents. Diacritical marks can appear both above and below a letter, inside a letter, and between two letters. Diacritical marks can be used in combination with alphanumeric characters to produce a character that is not present in the character set (encoding) used in the page.
HTML Symbol Entities
HTML entities were described in the previous chapter. Many mathematical, technical, and currency symbols are not present on a normal keyboard. To add these symbols to an HTML page, you can use an HTML entity name. If no entity name exists, you can use an entity number; a decimal (or hexadecimal) reference.
Example:
<p>I will display €</p>
<p>I will display €</p>
<p>I will display €</p>
Result: I will display β¬ (all three methods produce the same euro symbol)
π‘ Why this matters: HTML symbol entities allow you to display mathematical, technical, and currency symbols that are not available on standard keyboards, ensuring proper rendering across all browsers.
Some Mathematical Symbols Supported by HTML include: β (FOR ALL), β (PARTIAL DIFFERENTIAL), β (THERE EXISTS), β (EMPTY SETS), β (NABLA), β (ELEMENT OF), β (NOT AN ELEMENT OF), β (CONTAINS AS MEMBER), β (N-ARY PRODUCT), β (N-ARY SUMMATION).
Some Greek Letters Supported by HTML include: Ξ (ALPHA), Ξ (BETA), Ξ (GAMMA), Ξ (DELTA), Ξ (EPSILON), Ξ (ZETA).
Character Encoding
ASCII was the first character encoding standard (also called character set). It defines 127 different alphanumeric characters that could be used on the internet. ASCII supported numbers (0-9), English letters (A-Z), and some special characters like ! $ + - ( ) @ < >.
ANSI (Windows-1252) was the original Windows character set. It supported 256 different character codes. ISO-8859-1 was the default character set for HTML 4. It also supported 256 different character codes. Because ANSI and ISO were limited, the default character encoding was changed to UTF-8 in HTML5.
UTF-8 (Unicode) covers almost all of the characters and symbols in the world.
The HTML charset Attribute: To display an HTML page correctly, a web browser must know the character set used in the page. This is specified in the <meta> tag.
For HTML4: <meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1">
For HTML5: <meta charset="UTF-8">
The ASCII Character Set:
- Uses values from 0 to 31 (and 127) for control characters
- Uses values from 32 to 126 for letters, digits, and symbols
- Does not use values from 128 to 255
The ANSI Character Set (Windows-1252):
- Identical to ASCII for values 0 to 127
- Has proprietary characters for values 128 to 159
- Identical to UTF-8 for values 160 to 255
The ISO-8859-1 Character Set:
- Identical to ASCII for values 0 to 127
- Does not use values 128 to 159
- Identical to UTF-8 for values 160 to 255
The UTF-8 Character Set:
- Identical to ASCII for values 0 to 127
- Does not use values 128 to 159
- Identical to both ANSI and 8859-1 for values 160 to 255
- Continues from value 256 with more than 10,000 different characters
URL Structure
A URL (Uniform Resource Locator) is another word for a web address. A URL can be composed of words (google.com) or an Internet Protocol (IP) address (192.68.20.50). Web browsers request pages from web servers by using a URL.
A URL like http://www.htmllectures.com/html/default.asp follows this syntax:
scheme://host.domain:port/path/filename
- scheme - defines the type of Internet service (most common is http)
- host - defines the domain host (default host for http is www)
- domain - defines the Internet domain name (google.com)
- port - defines the port number at the host (default for http is 80)
- path - defines a path at the server (If omitted: the root directory of the site)
- filename - defines the name of a document or resource
Common URL Schemes:
- http - HyperText Transfer Protocol - Common web pages. Not encrypted
- https - Secure HyperText Transfer Protocol - Secure web pages. Encrypted
- ftp - File Transfer Protocol - Downloading or uploading files
- file - A file on your computer
URL Encoding
URLs can only be sent over the Internet using the ASCII character-set. Since URLs often contain characters outside the ASCII set, the URL has to be converted into ASCII. URL encoding converts characters into a format that can be transmitted over the Internet.
URL encoding replaces non-ASCII characters with a "%" followed by hexadecimal digits. URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign, or %20.
β Key Takeaways
The <head> element is essential for storing metadata like title, styles, scripts, and character encoding information that browsers and search engines use to understand and display your web page correctly. HTML entities and symbol entities allow you to display reserved characters and special symbols that are not available on standard keyboards using &entity_name; or &#entity_number; syntax. Character encoding standards have evolved from ASCII (127 characters) through ANSI and ISO-8859-1 (256 characters) to UTF-8 which supports over 10,000 characters and is the default for HTML5. URLs follow the syntax scheme://host.domain:port/path/filename and must be URL-encoded to replace non-ASCII characters with % followed by hexadecimal digits for proper transmission over the Internet.
π§ Quick Revision Questions
- What are the six tags that describe metadata in the HTML
<head>element? - How do you display a less than sign (<) in HTML without it being interpreted as a tag?
- What is the difference between ASCII, ANSI, ISO-8859-1, and UTF-8 character sets in terms of the number of characters they support?
- What is the correct HTML5 syntax for specifying the character set in a webpage?
- What are the components of a URL and what does URL encoding do to non-ASCII characters?
π Lecture 27 β HTML and XHTML
π Overview: This lecture introduces XHTML (Extensible HyperText Markup Language) as a stricter, XML-based version of HTML. It explains why XHTML was developed to address problems with "bad" HTML code, covers the key differences between HTML and XHTML, and provides guidelines for converting HTML to XHTML. The lecture also introduces CSS (Cascading Style Sheets), including its syntax, selectors, and methods of insertion into HTML documents.
ποΈ Topics Covered
The lecture covers the definition and purpose of XHTML, reasons for its development due to browser inconsistencies and poorly written HTML, the most important differences from HTML including document structure rules, element and attribute requirements (proper nesting, closing, lowercase, quoting), mandatory DOCTYPE and namespace declarations, and a step-by-step guide for converting from HTML to XHTML. It then transitions to CSS, covering its definition as a style sheet language, basic syntax with selectors and declarations, CSS comments, various CSS selectors (classes, IDs, elements, combinators, attributes), and three methods of inserting CSS (external, internal, and inline style sheets).
π Lecture Summary
What Is XHTML?
XHTML stands for Extensible HyperText Markup Language. It is almost identical to HTML but is stricter and defined as an XML application. XHTML is supported by all major browsers.
Why XHTML?
Many web pages contain "bad" HTML that, while functional, does not follow proper rules. With the variety of browser technologies, including mobile phones and small devices that lack resources to interpret incorrect markup, a stricter standard was needed. XML requires documents to be "well-formed," so by combining the strengths of HTML and XML, XHTML was developed. XHTML is essentially HTML redesigned as XML.
π Definition β XHTML: A stricter, XML-based version of HTML that requires documents to be well-formed and properly structured.
The Most Important Differences from HTML: Document Structure
- The XHTML DOCTYPE is mandatory
- The xmlns attribute in the
<html>element is mandatory - The elements
<html>,<head>,<title>, and<body>are all mandatory
XHTML Elements and Attributes
XHTML requires that elements be properly nested, always closed, and written in lowercase. Documents must have one root element. Attribute names must be in lowercase, attribute values must be quoted, and attribute minimization is forbidden.
π Example (Proper Nesting):
Incorrect: <b><i>This text is bold and italic</b></i>
Correct: <b><i>This text is bold and italic</i></b>
π Example (Elements Must Be Closed):
Incorrect: <p>hi, everyone <p>How are you?
Correct: <p>hi, everyone</p> <p>How are you?</p>
π Example (Empty Elements Must Also Be Closed):
A break: <br />
A horizontal rule: <hr />
An image: <img src="happy.gif" alt="Happy face" />
π Example (Lowercase Elements):
Incorrect: <BODY> <P>Hi, Everyone</P> </BODY>
Correct: <body> <p>Hi, Everyone</p> </body>
< !DOCTYPE .... > Is Mandatory
An XHTML document must have an XHTML DOCTYPE declaration. The <html>, <head>, <title>, and <body> elements must also be present, and the xmlns attribute in <html> must specify the XML namespace for the document.
How to Convert from HTML to XHTML
- Add an XHTML
<!DOCTYPE>to the first line of every page - Add an xmlns attribute to the html element of every page
- Change all element names to lowercase
- Close all empty elements
- Change all attribute names to lowercase
- Quote all attribute values
π‘ Why this matters: Following these conversion steps ensures your web pages are valid XHTML and will render correctly across all modern browsers and devices.
CSS (Cascading Style Sheets)
CSS is a style sheet language used for describing the presentation of a document written in a markup language. CSS defines how HTML elements are to be displayed. CSS styles were added to HTML 4.0 to solve presentation problems. Styles are normally stored in an external .css file, allowing you to change the style of an entire site by editing just that one file.
π Definition β CSS (Cascading Style Sheets): A style sheet language used for describing the presentation of a document written in a markup language, separating content from design.
CSS Syntax
CSS syntax consists of a selector and a declaration block. The selector points to the HTML element you want to style, and the declaration block contains one or more declarations separated by semicolons. Each declaration has a property name and a value, separated by a colon.
π Example (Basic CSS Syntax):
h1 {
color: blue;
font-size: 12px;
}
h1is the selectorcolor: blue;andfont-size: 12px;are declarationscolorandfont-sizeare property namesblueand12pxare values
CSS comments start with /* and end with */.
30- CSS Selectors
CSS selectors are patterns used to select the element(s) you want to style.
π Examples of Important CSS Selectors:
.classβ selects all elements withclass="intro"(CSS1)#idβ selects the element withid="firstname"(CSS1)elementβ selects all<p>elements (CSS1)element>elementβ selects all<p>elements where the parent is a<div>element (CSS2)element1~element2β selects every<ul>element preceded by a<p>element (CSS3)[attribute]β selects all elements with a target attribute (CSS2)[attribute=value]β selects all elements withtarget="_blank"(CSS2)[attribute|=value]β selects all elements with a lang attribute value starting with "en" (CSS2)
31- CSS Insertion (How to Insert CSS in HTML File)
CSS can be inserted into HTML documents using three methods: external style sheets, internal style sheets, or inline styles.
External Style Sheet
Each page includes a reference to the external CSS file using the <link> element inside the <head> section.
π Example:
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
Internal Style Sheet
Internal styles are defined within the <style> element inside the <head> section of an HTML page, used when a single page has a unique style.
π Example:
<head>
<style>
body {background-color: linen;}
h1 {color: maroon; margin-left: 40px;}
</style>
</head>
β Key Takeaways
XHTML is a stricter version of HTML defined as an XML application, requiring proper document structure with mandatory DOCTYPE, namespace, and core elements. All XHTML elements must be properly nested, closed (including empty elements with a trailing slash), and in lowercase, while attributes must be lowercase, quoted, and never minimized. CSS is a style sheet language used to describe presentation, separating content from design, with syntax consisting of selectors and declaration blocks. CSS can be applied via external files (linked in <head>), internal <style> blocks, or inline styles, with selectors ranging from simple (class, ID, element) to complex (combinators, attribute selectors) across CSS1, CSS2, and CSS3 versions.
π§ Quick Revision Questions
- What does XHTML stand for, and how is it different from HTML?
- List three mandatory elements that must be present in every XHTML document.
- Why must empty elements like
<br>be written with a trailing slash in XHTML? - What is the CSS syntax structure, and what does each part represent?
- Name two CSS selectors and give an example of what each one selects.
π Lecture 33 β 33a- CSS Text and Fonts
π Overview: This lecture covers CSS styling properties for text and fonts, including text color, transformation, indentation, and comprehensive font-family, style, and size control. It extends into practical styling applications for links, lists, tables, and the CSS box model, which are fundamental for web design and layout.
ποΈ Topics Covered
This lecture explains text properties like color, transformation, and indentation; font properties including family, style, and size with absolute and relative units; link styling with states and decorations; list styling with markers and images; table styling with borders, alignment, padding, and colors; the CSS box model with content, padding, border, and margin; and border and outline properties.
π Lecture Summary
CSS Text and Fonts
The CSS color property is used to set the color of the text. With CSS, a color is most often specified by a HEX value like "#ff0000", an RGB value like "rgb(255,0,0)", or a color name like "red". The default color for a page is defined in the body selector.
π Definition β Text Transformation: The text-transform property specifies uppercase and lowercase letters in a text. It can turn everything into uppercase or lowercase, or capitalize the first letter of each word.
π Example:
p.uppercase {text-transform: uppercase;}p.lowercase {text-transform: lowercase;}p.capitalize {text-transform: capitalize;}
π Definition β Text Indentation: The text-indent property specifies the indentation of the first line of a text or paragraph.
π Definition β CSS Font: CSS font properties define the font family, boldness, size, and the style of a text.
π Definition β CSS Font Families: There are two types of font family names: generic family (a group of font families with a similar look like "Serif" or "Monospace") and font family (a specific font family like "Times New Roman" or "Arial").
π The table shows:
- Serif (e.g., Times New Roman, Georgia): have small lines at the ends on some characters
- Sans-serif (e.g., Arial, Verdana): "Sans" means without, these fonts do not have the lines at the ends of characters
- Monospace (e.g., Courier New, Lucida Console): all characters have the same width
π Definition β Font Family: The font-family property should hold several font names as a "fallback" system. If the browser does not support the first font, it tries the next font. If the name of a font family is more than one word, it must be in quotation marks.
π Example: p { font-family: "Times New Roman", Times, serif; }
π Definition β CSS Font Style: The font-style property is mostly used to specify italic text, with three values: normal (text shown normally), italic (text shown in italics), and oblique (text is "leaning", very similar to italic but less supported).
π Example:
p.normal {font-style: normal;}p.italic {font-style: italic;}p.oblique {font-style: oblique;}
π Definition β Font Size: The font-size property sets the size of the text. Being able to manage text size is important in web design. The font-size value can be absolute or relative. Absolute size sets the text to a specified size and does not allow a user to change the text size in all browsers (bad for accessibility). Relative size sets the size relative to surrounding elements and allows a user to change the text size in browsers.
π Set Font Size with Pixels: Setting the text size with pixels gives you full control over the text size. Example:
h1 {font-size: 40px;}h2 {font-size: 30px;}p {font-size: 14px;}
π Formula: pixels/16 = em β 1em is equal to the current font size. The default text size in browsers is 16px. π Example: In CSS, the em size unit is recommended by the W3C to allow users to resize text.
π Use a Combination of Percent and Em: The solution that works in all browsers is to set a default font-size in percent for the <body> element.
Example:
body {font-size: 100%;}h1 {font-size: 2.5em;}h2 {font-size: 1.875em;}p {font-size: 0.875em;}
CSS Links
Styling Links: Links can be styled with any CSS property. Below example is used to give a specific color to all the link text in a file.
π Example: a {color: #FF0000;}
π Definition β The four link states are:
a:link- a normal, unvisited linka:visited- a link the user has visiteda:hover- a link when the user mouses over ita:active- a link the moment it is clicked
π Definition β Text Decoration: This property is mostly used to remove underlines from links. π Example:
a:link {text-decoration: none;}β to remove the link decorationa:visited {text-decoration: none;}β to remove the visited link's decorationa:hover {text-decoration: underline;}β underline the link text while mouse overa:active {text-decoration: underline;}β underline the active link
π Definition β Background Color: The background-color property specifies the background color for links.
π Example: a:link {background-color: #B2FF99;}
CSS Lists
In CSS, the list properties allow you to set different list item markers for ordered and unordered lists, and set an image as the list item marker.
π Definition β Lists in HTML: There are two types of lists: unordered lists (<ul>) where list items are marked with bullets, and ordered lists (<ol>) where list items are marked with numbers or letters. The type of list item marker is specified with the list-style-type property.
π Example:
ul.a {list-style-type: circle;}ul.b {list-style-type: square;}ol.c { list-style-type: upper-roman;}ol.d {list-style-type: lower-alpha;}
π Definition β An Image as the List Item Marker: To specify an image as the list item marker, use the list-style-image property.
π Example: ul { list-style-image: url('sqpurple.gif');}
π Definition β List - Shorthand property: The list-style property is a shorthand property used to set all the list properties in one declaration.
π Example: ul {list-style: square inside url("sqpurple.gif");}
CSS Tables
The look of an HTML table can be greatly improved with CSS.
π Definition β Table Borders: To specify table borders in CSS, use the border property.
π Example: table, th, td { border: 1px solid black;}
π Definition β Double Borders: Notice that the table in the example above has double borders because both the table and the <th>/<td> elements have separate borders. To display a single border for the table, use the border-collapse property.
π Example: table {border-collapse: collapse;} table, th, td {border: 1px solid black;}
π Definition β Table Width and Height: Width and height of a table is defined by the width and height properties.
π Example: table {width: 100%;} th {height: 50px;}
π Definition β Horizontal Text Alignment: The text-align property sets the horizontal alignment (left, right, or center). By default, text in <th> elements are center-aligned and text in <td> elements are left-aligned.
π Example: th {text-align: left;}
π Definition β Vertical Text Alignment: The vertical-align property sets the vertical alignment (top, bottom, or middle). By default, the vertical alignment of text in a table is middle (for both <th> and <td> elements).
π Example: td { height: 50px; vertical-align: bottom;}
π Definition β Table Padding: To control the space between the border and content in a table, use the padding property on <td> and <th> elements.
π Example: td {padding: 15px;}
π Definition β Table Color: We can specify using CSS the color of the borders, and the text and background color of <th> elements.
π Example: table, td, th {border: 1px solid green;} th {background-color: green; color: white;}
CSS Box Model
All HTML elements can be considered as boxes. 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 HTML elements and consists of: margins, borders, padding, and the actual content. The box model allows us to add a border around elements and to define space between elements.
π Definition β The different parts of the box model:
- 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
π Example: div {width: 300px; padding: 25px; border: 25px solid navy; margin: 25px;}
π Definition β 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: To style a <div> element to have a total width of 350px: div {width: 320px; padding: 10px; border: 5px solid gray; margin: 0; }
π‘ Why this matters: The total width of an element is calculated by adding the width, padding, border, and margin. Without understanding the box model, you cannot predict the actual space an element occupies on the page.
CSS Border and Outline
π Definition β Border Style: The border-style property specifies what kind of border to display. Common values include solid, dotted, dashed, double, groove, ridge, inset, and outset.
π Definition β Border Width: The border-width property sets the width of the border in pixels or using pre-defined values: thin, medium, or thick. Note: The "border-width" property does not work if used alone; use the "border-style" property to set the borders first.
π Example:
p.one {border-style: solid; border-width: 5px;}p.two { border-style: solid; border-width: medium;}
π Definition β Border Color: The border-color property sets the color of the border. Color can be set by name (like "red"), RGB (like "rgb(255,0,0)"), or Hex (like "#ff0000"). If the border color is not set, it is inherited from the color property of the element.
π Example:
p.one { border-style: solid; border-color: red; }p.two {border-style: solid; border-color: #98bf21; }
π Definition β Border - Individual sides: In CSS, it is possible to specify different borders for different sides.
π Example: p { border-top-style: dotted; border-right-style: solid; border-bottom-style: dotted; border-left-style: solid;}
π Definition β Border - Shorthand property: The border property is shorthand for the individual border properties: border-width, border-style (required), and border-color.
π Definition β CSS Outlines: An outline is a line drawn around elements (outside the borders) to make the element "stand out". The outline properties specify the style, color, and width of an outline. The outline is different from the border property because the outline is not a part of an element's dimensions; the element's total width and height is not affected by the width of the outline.
π Example: p {border: 1px solid red; outline: green dotted thick; }
β Key Takeaways
For the exam, you must know the four CSS text properties (color, transformation, indentation, and font properties) with their correct syntax. You need to memorize the four link states (link, visited, hover, active) and how to style them using text-decoration and background-color. For tables, remember that border-collapse removes double borders, and that text-align and vertical-align control alignment. The CSS box model is critical: the total width of an element equals width + padding + border + margin. Finally, understand that outlines differ from borders as they do not affect element dimensions.
π§ Quick Revision Questions
- What are the four ways to specify color in CSS text, and provide one example for each method?
- Explain the difference between absolute and relative font sizing, and give an example of using em units.
- What are the four link states in CSS and the correct order in which they should be defined?
- How do you remove double borders in a CSS table, and what is the default vertical alignment of text in table cells?
- What are the four components of the CSS box model, and how does the outline property differ from the border property in terms of element dimensions?
π Lecture 40 β CSS Margin and Padding
π Overview: This lecture covers the core CSS properties for controlling spacing around and within HTML elements. It explains how margins create transparent space outside element borders, while padding creates space between the border and content, and then expands into related topics like dimensions, alignment, positioning, floats, and combinators for complete layout control.
ποΈ Topics Covered
This lecture begins with CSS margin properties including individual sides and shorthand notation, then moves to CSS padding with similar individual and shorthand approaches. It continues with CSS dimension properties for controlling height and width, CSS align techniques including center, left/right alignment using margin, position, and float properties. The lecture also covers CSS display properties (block vs inline elements, hiding elements), CSS positioning methods (static, fixed, relative, absolute), overlapping elements with z-index, CSS float and clear properties, and concludes with CSS combinators (descendant, child, adjacent sibling, and general sibling selectors).
π Lecture Summary
CSS Margin
The CSS margin properties define the space around elements. The margin clears an area around an element (outside the border). The margin does not have a background color, and is completely transparent. The top, right, bottom, and left margin can be changed independently using separate properties. A shorthand margin property can also be used to change all margins at once.
Possible values for margin properties include: auto (the browser calculates a margin), length (specifies a margin in px, pt, cm, etc., default value is 0px), % (specifies a margin in percent of the width of the containing element), and inherit (specifies that the margin should be inherited from the parent element).
π Definition β Margin: The CSS property that defines the transparent space around an element, outside its border.
π Formula: margin: [top] [right] [bottom] [left] β The shorthand property specifying margins in clockwise order (top, right, bottom, left).
π Example: For a paragraph element, individual margins can be set: p { margin-top: 100px; margin-bottom: 100px; margin-right: 150px; margin-left: 50px; }. The shorthand p { margin: 100px 50px; } sets top/bottom to 100px and right/left to 50px. The four-value shorthand p { margin: 25px 50px 75px 100px; } sets top=25px, right=50px, bottom=75px, left=100px.
CSS Padding
The CSS padding properties define the space between the element border and the element content. It clears an area around the content (inside the border) of an element. The padding is affected by the background color of the element. The top, right, bottom, and left padding can be changed independently using separate properties. A shorthand padding property can also be used to change all paddings at once.
π Definition β Padding: The CSS property that defines the space between an element's border and its content, which is affected by the element's background color.
π Formula: padding: [top] [right] [bottom] [left] β The shorthand property specifying all padding values in clockwise order.
π Example: Individual padding: p { padding-top: 25px; padding-right: 50px; padding-bottom: 25px; padding-left: 50px; }. Shorthand p { padding: 25px 50px; } sets top/bottom to 25px and right/left to 50px. One-value shorthand padding: 25px sets all four paddings to 25px. Three-value shorthand padding: 25px 50px 75px sets top=25px, right/left=50px, bottom=75px.
π‘ Why this matters: Understanding the difference between margin (outside, transparent) and padding (inside, colored with background) is fundamental for creating proper spacing in web layouts.
CSS Dimension
The CSS dimension properties allow you to control the height and width of an element.
π Example: img { width: 200px; } sets an image width to 200px. p { min-height: 100px; background-color: yellow; } ensures a paragraph is at least 100px tall.
CSS Align
A block element is an element that takes up the full width available and has a line break before and after it. Examples include <h1>, <p>, and <div>.
Center Aligning Using the margin Property: Block elements can be center-aligned by setting the left and right margins to "auto". This specifies that they should split the available margin equally.
π Example: .center { margin-left: auto; margin-right: auto; width: 70%; background-color: #b0e0e6; }
Left and Right Aligning Using the position Property: One method of aligning elements is to use absolute positioning.
π Example: .right { position: absolute; right: 0px; width: 300px; background-color: #b0e0e6; }
Cross Browser Compatibility Issues: When aligning elements, it is always a good idea to predefine margin and padding for the <body> element to avoid visual differences in different browsers. IE8 and earlier, when using the position property without a !DOCTYPE declaration, will add a 17px margin on the right side.
π Example: body { margin: 0; padding: 0; } .container { position: relative; width: 100%;} .right { position: absolute; right: 0px; width: 300px; background-color: #b0e0e6; }
Left and Right Aligning Using the float Property: One method of aligning elements is to use the float property.
π Example: .right { float: right; width: 300px; background-color: #b0e0e6; }
π‘ Why this matters: Cross-browser compatibility requires proper DOCTYPE declaration and resetting body margins/padding when using absolute positioning.
CSS Display
The display property specifies if/how an element is displayed, and the visibility property specifies if an element should be visible or hidden.
Hiding an Element - display: none or visibility: hidden: These two methods produce different results. Visibility: hidden hides an element, but it will still take up the same space as before and affect the layout. Display: none hides an element completely, and it will not take up any space.
π Example: h1.hidden {visibility: hidden;} hides the heading but keeps its space. h1.hidden {display: none;} hides the heading and removes its space from the layout.
Block and Inline Elements: A block element takes up the full width available and has a line break before and after it (e.g., <h1>, <p>, <li>, <div>). An inline element only takes up as much width as necessary and does not force line breaks (e.g., <span>, <a>).
Changing How an Element is displayed: Changing an inline element to a block element, or vice versa, can be useful for making the page look a specific way.
π Example: li {display: inline;} displays list items as inline elements.
CSS Positioning & Floats
The CSS positioning properties allow you to position an element. Elements can be positioned using the top, bottom, left, and right properties, but these will not work unless the position property is set first.
There are four different positioning methods:
1- Static Positioning: HTML elements are positioned static by default. A static positioned element is always positioned according to the normal flow of the page and is not affected by the top, bottom, left, and right properties.
2- Fixed Positioning: An element with a fixed position is positioned relative to the browser window and will not move even if the window is scrolled. Fixed positioned elements are removed from the normal flow and can overlap other elements.
π Example: p.pos_fixed { position: fixed; top: 30px; right: 5px; }
3- Relative Positioning: A relative positioned element is positioned relative to its normal position. The content can be moved and overlap other elements, but the reserved space for the element is still preserved in the normal flow. Relatively positioned elements are often used as container blocks for absolutely positioned elements.
π Example: h2.pos_left { position: relative; left: -20px; } moves the element 20px to the left of its normal position. h2.pos_top { position: relative; top: -50px; } moves it 50px upward.
4- Absolute Positioning: An absolute positioned element is positioned relative to the first parent element that has a position other than static. If no such element is found, the containing block is <html>. Absolutely positioned elements are removed from the normal flow and can overlap other elements.
π Example: h2 { position: absolute; left: 100px; top: 150px; }
Overlapping Elements: When elements are positioned outside the normal flow, they can overlap other elements. The z-index property specifies the stack order of an element. An element with greater stack order is always in front of an element with a lower stack order. An element can have a positive or negative stack order.
π Example: img { position: absolute; left: 0px; top: 0px; z-index: -1; } places the image behind other elements.
CSS Float: With CSS float, an element can be pushed to the left or right, allowing other elements to wrap around it. Elements are floated horizontally (left or right, not up or down). A floated element will move as far to the left or right as it can. The elements after the floating element will flow around it, while elements before it are not affected.
π Example: img { float: right; } floats an image to the right, and following text flows around it to the left.
Turning off Float - Using Clear: Elements after the floating element will flow around it. To avoid this, use the clear property, which specifies which sides of an element other floating elements are not allowed.
π‘ Why this matters: Understanding the four positioning methods and how z-index works is critical for creating complex layouts where elements need to overlap or stay fixed during scrolling.
CSS Combinators
A combinator explains the relationship between the selectors. A CSS selector can contain more than one simple selector, and between them, we can include a combinator. There are four different combinators in CSS3:
Descendant Selector: The descendant selector matches all elements that are descendants of a specified element. It uses a space between selectors.
π Example: div p { background-color: yellow; } selects all <p> elements inside <div> elements (at any nesting level).
Child Selector: The child selector selects all elements that are the immediate children of a specified element. It uses the > symbol.
π Example: div > p { background-color: yellow; } selects all <p> elements that are direct children of a <div> element.
Adjacent Sibling Selector: The adjacent sibling selector selects all elements that are the adjacent siblings of a specified element. Sibling elements must have the same parent element, and "adjacent" means "immediately following". It uses the + symbol.
π Example: div + p { background-color: yellow; } selects <p> elements placed immediately after <div> elements.
General Sibling Selector: The general sibling selector selects all elements that are siblings of a specified element. It uses the ~ symbol.
π Example: div ~ p { background-color: yellow; } selects all <p> elements that are siblings of <div> elements.
β Key Takeaways
Margins create transparent space outside element borders and do not show background color, while paddings create space inside borders and are affected by the element's background color. Both properties support individual side control and shorthand notation with 1-4 values following the clockwise order (top, right, bottom, left). The display property offers two ways to hide elements: visibility:hidden keeps the space, while display:none removes the element entirely. CSS positioning has four methods (static default, fixed to viewport, relative to normal position, and absolute to nearest positioned ancestor), with z-index controlling stack order. Combinators (descendant, child, adjacent sibling, general sibling) define specific relationships between selectors for targeted styling.
π§ Quick Revision Questions
- What is the difference between margin and padding in terms of background color visibility?
- Using the shorthand property
padding: 10px 20px 30px 40px;, what are the individual padding values for top, right, bottom, and left? - How do
visibility: hiddenanddisplay: nonediffer when hiding an element? - What are the four CSS positioning methods, and how does absolute positioning determine its containing block?
- What symbol does the child selector use to select immediate children, and how does it differ from the descendant selector?
π Lecture 44 β CSS Pseudo-Class
π Overview: This lecture introduces CSS pseudo-classes, which are used to define special states of elements. It covers how to style elements based on user interaction and document structure, including anchor links, first-child elements, and language-specific styling, enabling dynamic and context-sensitive web designs.
ποΈ Topics Covered
The lecture covers what pseudo-classes are and their syntax, anchor pseudo-classes for different link states, combining pseudo-classes with CSS classes, the :first-child pseudo-class for targeting first child elements, and the :lang pseudo-class for language-specific styling. Examples and code snippets demonstrate each concept.
π Lecture Summary
What are Pseudo-classes?
A pseudo-class is used to define a special state of an element. For example, it can be used to style an element when a user's mouse is over it, or to style visited and unvisited links differently.
The syntax of pseudo-classes is:
selector:pseudo-class {
property:value;
}
Anchor Pseudo-classes
Links can be displayed in different ways using these four pseudo-classes:
a:linkβ styles unvisited linksa:visitedβ styles visited linksa:hoverβ styles when the mouse is over the linka:activeβ styles the selected link
/* unvisited link */
a:link {
color: #FF0000;
}
/* visited link */
a:visited {
color: #00FF00;
}
/* mouse over link */
a:hover {
color: #FF00FF;
}
/* selected link */
a:active {
color: #0000FF;
}
π Definition β Pseudo-class: A keyword added to a selector that specifies a special state of the selected element(s).
π Example: The a:hover pseudo-class changes the link color to #FF00FF (magenta) when the user hovers the mouse over it.
Pseudo-classes and CSS Classes
Pseudo-classes can be combined with CSS classes.
a.highlight:hover {
color: #ff0000;
}
π Example: When you hover over the link with class highlight, it will change color to red (#ff0000).
CSS - The :first-child Pseudo-class
The :first-child pseudo-class matches a specified element that is the first child of another element.
Example 1: Selects any <p> element that is the first child of any element:
p:first-child {
color: blue;
}
Example 2: Selects the first <i> element in all <p> elements:
p i:first-child {
color: blue;
}
Example 3: Selects all <i> elements in <p> elements that are the first child of another element:
p:first-child i {
color: blue;
}
CSS - The :lang Pseudo-class
The :lang pseudo-class allows you to define special rules for different languages.
Note: IE8 supports the :lang pseudo-class only if a <!DOCTYPE> is specified.
π Example: The :lang class defines the quotation marks for <q> elements with lang="no" (Norwegian):
q:lang(no) {
quotes: "~" "~";
}
β Key Takeaways
Pseudo-classes are essential for creating interactive and context-sensitive web designs. The four anchor pseudo-classes (:link, :visited, :hover, :active) must be used in this specific order for proper link styling. The :first-child pseudo-class targets elements that are the first child of their parent, and its behavior changes based on selector positioning. The :lang pseudo-class enables language-specific styling, which is crucial for international websites. Pseudo-classes can be combined with regular CSS classes for more specific targeting.
π§ Quick Revision Questions
- What is the correct syntax for writing a pseudo-class in CSS?
- What are the four anchor pseudo-classes, and in what order should they be defined?
- How does
p:first-child idiffer fromp i:first-childin terms of what elements they select? - What special requirement is needed for IE8 to support the
:langpseudo-class? - How can you combine a pseudo-class with a regular CSS class? Provide an example.