Lecture 5 - CSS Flashcards
Benefits of CSS
- Improved control over formatting.
- Improved site maintainability.All formatting can be centralized into one CSS file
- Improved accessibility.By keeping presentation out of the HTML, screen readers and other accessibility tools work better.
- Improved page-download speed.Each individual HTML file will contain less style information and markup, and thus be smaller.
- Improved output flexibility.CSS can be used to adopt a page for different output media. This approach to CSS page design is often referred to asresponsive design.
What is CSS
- CSS is a W3C standard for describing the appearance of HTML elements.
- With CSS, we can assign font properties, colors, sizes, borders, background images, positioning and even animate elements on the page.
- CSS can be added directly to any HTML element (via the style attribute), within the
<head>
element, or, most commonly, in a separate text file that contains only CSS.
CSS Versions
- Style sheets as a way to visually format markup predate the web.
- W3C decided to adopt CSS, and by the end of 1996, the CSS Level 1 Recommendation was published
- A year later, the CSS2 was published
- CSS2.1, did not become an official W3C Recommendation until June 2011
- At the same time the CSS2.1 standard was being worked on, a different group at the W3C was working on a CSS3 draft
Browser Adoption
- Perhaps the most important thing to keep in mind with CSS is that the different browsers have not always kept up with the W3C.
- For this reason, CSS has a reputation for being a somewhat frustrating language
CSS Syntax
- a CSS document consists of one or more style rules
1. Style Rule: Each rule consists of a selector and a declaration block.selector { property: value; property2: value2; }
-
Selector: Identifies the HTML element(s) to be styled.
em
-
Declaration Block: Enclosed within curly braces
{}
, it contains one or more declarations.{ color: red; }
-
Declaration: A single property-value pair.
color: red;
-
Property: The aspect of the element to be styled.
color
-
Value: The style to be applied to the property.
red
Common Units of Measure Values
Units of measure in CSS are either:
- relative units, in that they are based on the value of something else, or
- absolute units, in that they have a real-world size.
Some example measures (See Table 4.3 for more):
- pxPixel. In CSS2 this is a relative measure, while in CSS3 it is absolute (1/96 of an inch)
- emEqual to the computed value of the font-size property of the element on which it is used.
- % A measure that is always relative to another value.
- inInches
- cmCentimeters
Inline Styles
Inline Styles
- CSS rules that are applied directly within an HTML element using the
style
attribute. - They only affect the specific element they are defined within and override any other style definitions for the properties used.
- A selector is not necessary.
```
<h1>Share Your Travels</h1><h2 style=”font-size: 24pt”>Description</h2>
…
<h2 style=”font-size: 24pt; font-weight: bold;”>Reviews</h2>
```
Embedded Style Sheet
Embedded Style Sheet
- Embedded style sheets (also known as internal styles) are CSS rules placed within the
<style>
element inside the<head>
section of an HTML document. - While they are better than inline styles for maintainability and separation of concerns, they are still generally discouraged in favor of external stylesheets for larger projects.
```
<!DOCTYPE html>
<html>
<head>
<meta></meta>
<title>Chapter 4</title>
<style>h1 {font-size: 24pt;} h2 { font-size: 18pt; font-weight: bold; }
</style>
</head>
<body>
```
</body></html> - Placement: Defined within the
<style>
element inside the<head>
section. - Scope: Affect the entire document but do not apply to other documents.
- Separation: Better separation of content and presentation compared to inline styles.
External Style Sheet
- External style sheets are CSS rules placed within an external text file with the
.css
extension. - This method is widely preferred for most projects because it promotes better organization, maintainability, and performance.
- When you change an external style sheet, all HTML documents that reference that style sheet will automatically use the updated version.
- The browser can cache the external style sheet, reducing load times for users who visit multiple pages that use the same stylesheet.
/* styles.css */ h1 { font-size: 24pt; } h2 { font-size: 18pt; font-weight: bold; } p { font-size: 14pt; }
How to use the external style sheet
-
Create the External CSS File: Create a text file with the
.css
extension, e.g.,styles.css
. - Add CSS Rules to the File: Write your CSS rules in this file.
-
Link the CSS File in HTML: Use the
<link>
element to reference the CSS file in the<head>
section of your HTML document.
Benefits of using external style sheets
- Reusability: One CSS file can be linked to multiple HTML documents, ensuring consistent styling across a website.
- Maintainability: Easier to maintain and update styles since changes in the CSS file will automatically reflect across all linked HTML documents.
- Separation of Concerns: Keeps HTML content separate from CSS presentation, promoting cleaner and more organized code.
The Document Object Model
- Internal Representation: The DOM is how a browser internally represents an HTML page.
- Tree Structure: The DOM is like a tree, representing the overall hierarchical structure of the document.
- Hierarchy Terminology: In the DOM, elements are often referred to with familial terms, such as descendants, ancestors, and siblings, based on their position within the hierarchy.
Hierachical Structure of DOM
In the DOM:
- Root: The document itself is the root of the tree.
- Nodes: Elements, attributes, and text are considered nodes in the tree.
- Parent and Child: Each element and attribute has a parent node, and can have multiple child nodes.
- Siblings: Nodes that share the same parent are considered siblings.
Element Selectors
- Element selectorsselect all instances of a given HTML element.
- You can also select all elements by using theuniversal element selector(*)
- You can select a group of elements by separating the different element names with commas.
```css
/* commas allow you to group selectors */
p, div, aside {
margin: 0;
padding: 0;
}
/* the above single grouped selector is equivalent to the following: */
p {
margin: 0;
padding: 0;
}
div {
margin: 0;
padding: 0;
}
aside {
margin: 0;
padding: 0;
}
~~~
Class Selectors
- Aclass selectorallows you to simultaneously target different HTML elements regardless of their position in the document tree.
- HTML elements labeled with the same class attribute value, can be targeted for styling by using a class selector, which takes the form: period (.) followed by the class name.
ID Selectors
- AnID selectorallows you to target a specific element by its id attribute regardless of its type or position in the document tree.
- HTML elements labeled with an id attribute, can be targeted for styling by using an id selector, which takes the form: pound/hash (#) followed by the id name.
- Consider Figure 4.4. The original HTML can be modified to add class and id values, which are then styled in CSS.
- Id selector #firstmatches the div with id “first”
- Class selectors .orangeand .circle, match all divs with those class values.
- Notice that an element can be tagged with multiple classes.
Attribute Selectors
Anattribute selectorprovides a way to select HTML elements either by the presence of an element attribute or by the value of an attribute.
- Attribute selectors can be helpful in the styling of hyperlinks and form elements (which come up in the next chapter)
- These selectors can be combined with the element id and class selectors.
- You use square brackets to create attribute selectors
Matches in Attribute Selectors
[ ]
- A specific attribute
[=]
- A specific attribute with a specific value
a[href^="mailto"]
- Matches any <a>
element whose href attribute begins with “mailto“
a[href$=".pdf"]
- Matches any <a>
element whose href attribute ends with the text “.pdf“
[~=]
- A specific attribute whose value matches at least one of the words in a space-delimited list of words
[^=]
- A specific attribute whose value begins with a specified value
[$=]
- A specific attribute whose value ends with a specified value
[*=]
- A specific attribute whose value contains a substring
Pseudo-Element and Pseudo-Class Selectors
Apseudo-element selectoris a way to select something that does not exist explicitly as an element in the HTML document tree.
- You can select thefirst lineorfirst letterof any HTML element using a pseudo-element selector.
Apseudo-class selectortargets either a particular state or a variety of family relationships
- This type of selector is for targeting link states and for adding hover styling for other elements
Common Pseudo Selectors
- a:linkSelects links that have not been visited.
- a:visitedSelects links that have been visited.
- :hoverSelects elements that the mouse pointer is currently above.
- :activeSelects an element that is being activated by the user. A typical example is a link that is being clicked.
- :first-childSelects an element that is the first child of its parent.
- :first-letterSelects the first letter of an element.
- :first-lineSelects the first line of an element.
Contextual Selectors
Acontextual selector(in CSS3 also calledcombinators) allows you to select elements based on theirancestors,descendants, orsiblings.
- Adescendant selectormatches all elements that are contained within another element. The character used to indicate descendant selection is a space “ “
- Achild selectormatches a specified element that is a direct child of the specified element. The character used is a “>”
- AnAdjacent selectormatches a specified element that is the next sibling of the specified element. The character used is a “+”
- AGeneral selectormatches All following elements that shares the same parent as the specified element. The character used is a “~”
The Cascade: Inheritance
Inheritanceis the principle that many CSS properties affect their descendants as well as themselves.
- Font, color, list, and text properties (from Table 4.1) are inheritable;
- Layout, sizing, border, background, and spacing properties are not.
- it is also possible to inherit properties that are normally not inheritable using inherit
The Cascade: Specificity
Specificityis how the browser determines which style rule takes precedence when more than one style rule could be applied.
- The more specific selector takes precedence
- Class selectors take precedence over element selectors, and id selectors take precedence over class selectors
The Cascade: Location
- Finally, when inheritance and specificity cannot determine style precedence, the principle oflocationwill be used.
- When rules have the same specificity, then the latest are given more weight.
- For instance, an inline style will override one defined in an external author style sheet or an embedded style sheet.
The Box Model
In CSS, all HTML elements are represented by an element box, fundamental to understanding CSS.
Block Elements
- Block-level elements (e.g.,
<p>
,<div>
,<h2>
,<ul>
,<table>
) each occupy their own line. - Without styling, two block-level elements cannot exist on the same line.
- Block-level elements use the normal CSS box model.
Inline Elements
- Inline elements are displayed within lines and do not form their own blocks.
- Examples include
<em>
,<a>
,<img>
, and<span>
. - Content moves to a new line when there is not enough space left on the current line.
Margins and Padding
- Margins add spacing around an element’s content.
- Padding adds spacing within elements.
- Borders divide the margin area from the padding area.
Collapsing Margins
- Vertical margins of two elements touching will collapse, displaying only the largest margin value.
- Horizontal margins never collapse.
Borders
- Borders separate the margin area from the padding area.
- Properties can be set individually for each side (e.g.,
border-top-color
) or for all sides at once (e.g.,border-color
).
Box Dimensions
- Block-level elements have width, height, min-width, min-height, max-width, and max-height properties.
- The total size of an element equals the content area size plus padding, borders, and margins.
Box Dimensions
- Block-level elements have width, height, min-width, min-height, max-width, and max-height properties.
- The total size of an element equals the content area size plus padding, borders, and margins.
Border-Box Approach
The border-box approach simplifies the inclusion of margins, content, and borders by making the element’s width and height include padding and border.
Overflow Property
The overflow property controls what happens when content exceeds the box’s dimensions.
- visible
- hidden
- auto
- scroll
CSS Text Styling
- Font propertiesthat affect the font and its appearance.
- Paragraph propertiesthat affect the text in a similar way no matter which font is being used
- Many of the most common font properties are shown in Table 4.9 and include
- Font, font-family, font-style, font-size, font-variant, font-weight
CSS Variables
- Custom properties allowing the definition and reuse of variables in CSS.
- Defined with a double hyphen (
-
) usually within a:root
pseudo-class selector. - Referenced using the
var()
function.