CSS Fundamentals and Selectors Guide
CSS Fundamentals and Selectors Guide
Why CSS?
HTML markup: used to represent
• Semantic: e.g. <h1> means top-level heading
• Presentation: <h1> elements look a certain way (bold and big)
It is advisable to separate semantics from presentation:
• It’s easier to present documents on multiple platforms (browser,
cellphone, …)
• It’s easier to generate documents with consistent look
• Semantic and presentation changes can be made independently of one
another
HTML was NEVER intended to contain tags
for formatting a web page!
ĐẠI HỌC CẦN THƠ [Link]
CTU
4 Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
4
• Introduction to CSS
What is CSS?
A language that describes the style of an HTML document
describes how HTML elements should be displayed
Cascading Style Sheets removed the style formatting from the HTML page
CSS benefits:
• Easier to maintain and update
Cons: the
• Greater consistency in design compatibility with
• More formatting options the browsers
• Lightweight code
• Faster download times
• Ease of presenting different styles to different viewers, etc.
With CSS
No CSS
ĐẠI HỌC CẦN THƠ [Link]
CTU
6 Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
6
Content
1. Introduction to CSS
2. CSS levels and syntax
3. CSS selectors
4. CSS properties
5. Inheritance
6. The layout
7. The Box model
8. CSS convention
Levels of CSS
1. Inline:
specified for a specific occurrence of a tag and apply
only to that tag
appear in the tag itself
2. Internal (document):
apply to the whole document in which they appear
appear in the head of the document
3. External:
can be applied to any number of documents (entire
website)
defined in separate files
Levels of CSS
1. Inline: uses the style attribute of the HTML element
General form:
style="property1: value1; property_2: value2;…"
Example:
<!DOCTYPE html>
<html>
<body>
<h1 style="color:blue;">This is a Blue Heading</h1>
</body>
</html>
Levels of CSS
2. Internal: defined in the <head> section of an HTML page, within a
<style> element
General form: <html>
<style> <head>
<style>
rule list body {background-color: powderblue;}
</style> h1 {color: blue;}
p {color: red;}
Example:
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
ĐẠI HỌC CẦN THƠ [Link]
CTU
10 Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
10
• CSS Levels and Syntax
Levels of CSS
3. External:
• CSS rules are defined in a separate file (.css file)
• To use an external style sheet, add a link to it in the <head> section of
the HTML page
• Example:
<!DOCTYPE html>
body { <html>
background-color: powderblue; <head>
} <link rel="stylesheet" href="[Link]">
h1 { </head>
color: blue; <body>
} <h1>This is a heading</h1>
p { <p>This is a paragraph.</p>
color: red; </body>
} </html>
Levels of CSS
CSS conflict resolution:
When more than one style sheet applies to a specific tag in a document,
the lowest level style sheet has precedence
1. Inline CSS
2. Internal CSS
3. External CSS
4. Browser default format
CSS Syntax
A CSS block (internal) or CSS file (external) consists of CSS rules
A CSS rule consists of a selector and a declaration block surrounded by a
curly braces
The selector “selects” HTML elements in the webpage
A declaration block contains one or more declarations, separated by a
semicolon
Each declaration includes a CSS property name and a value
CSS Syntax
CSS declaration: { property: value; …}
CSS properties:
CSS3: more than 70 properties
CSS4: 129 properties
Categories (vary):
Fonts, lists, alignment, margins, colors, backgrounds, borders, positioning, etc.
Animations, backgrounds, box model, flexbox, grid, positioning, transitions, typography, etc.
CSS rule
CSS Syntax
CSS property values: vary in forms
Keywords: left, right, small, large, etc.
Number (with no space)
Unit: px (pixel), in (inches), cm, mm, pt (points), pc (picas, 12 pts), em (height of the
letter ‘m’), ex (height of the letter ‘x’), % (percentage), vw (view port width)
Color:
Name (140 color names)
Hex values, RGB (red, green, blue), RGBA (A: alpha channel), HLS (hue, saturation,
lightness), HLSA
Special values: normal (default value of the property), inherit (from parent element), auto
(browser default value)
HTML-Element Selector
Selects all HTML elements based on element name (HTML tag)
Syntax: HTML-tag { property: value; … }
Example:
p {
text-align: center;
color: red;
}
Class Selector
Selects elements with a specific class attribute
Syntax: .classname { property: value; … }
Example:
.header {
font-weight: bold;
}
ID Selector
Selects one unique element with a specific id attribute
Syntax: #id { property: value; … }
Example:
#para1 {
font-weight: bold;
}
Attribute Selector
Selects elements that have specific attributes or attribute values
Syntax:
• [attribute]: selects elements with specified attribute
Attribute Selector
Syntax (cont.):
• [attribute~="word"]: selects elements with an attribute value containing a specified
word (space-separated)
Attribute Selector
Syntax (cont.):
• [attribute|="word"]: selects elements with the specified attribute starting with the
specified word followed by a hyphen (-)
Attribute Selector
Syntax (cont.):
• [attribute$="value"]: selects elements whose attribute value ends with a specified
value
Special Selectors
Pseudo-classes:
Selects special elements that are not in the document tree
Prefixed with “:”
Pseudo Selection Example
:link all unvisited links a:link
:visited all visited links a:visited
:hover element with the mouse pointer hovering a:hover (hovered link)
:focus element which has the focus input:focus (focusing input)
:active the active element a:active (active link)
:first-child the first child of its parent p:first-child (first child <p>)
Special Selectors
Pseudo-classes: Examples:
Link
Special Selectors
Universal selector:
Selects all elements in the webpage
Syntax: *
Example: apply red color to all elements in the webpage
* {
color: red;
}
Combine Selectors
A CSS selector can contain more than one simple selector
Four CSS selector combinators:
1. Descendant selector (space)
2. Child selector (>)
Read from
3. Next sibling selector (+) right to left
4. Subsequent-sibling selector (~)
Example:
div#header p [Link] {
color: white;
}
ĐẠI HỌC CẦN THƠ [Link]
CTU
28 Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
28
• CSS Selectors
Combine Selectors
Descendant: select elements that are descendants of (inside) a specified
element (ascendant element)
Syntax: ascendant-selector __ descendant-selector
Example:
white space character: space, tab,
ul li { line feed, form feed, new line
color: blue;
}
Child: selects all elements that are direct children of a specified element
Example:
div > p {
background-color: yellow;
}
ĐẠI HỌC CẦN THƠ [Link]
CTU
29 Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
29
• CSS Selectors
Combine Selectors
Next sibling: select an element that is directly after a specific element
Example:
div + p {
background-color: yellow;
}
Subsequent-sibling: selects all elements that are next siblings of a
specified element
Example:
div ~ p {
background-color: yellow;
}
Group Selectors
Group selectors:
To share the same declaration to multiple selectors (to save space)
Syntax: use comma (,) to separate the grouped selector
Example:
<style>
a:hover, a:focus {
background-color: green;
}
a:hover { color: red; }
a:focus { color: yellow; }
</style>
Cascade Rule
Used to solve the conflicts occurring when there are two or more values for
the same property on the same element
Sources of conflict:
• Conflicting values between levels of style sheets
• Within one style sheet (overlapped selectors)
• Inheritance can cause conflicts
• Property values can come from style sheets written by the document author,
the browser user, and the browser defaults
Cascade Rule
Cascade (specificity precedence) rules: specificity, inheritance, and source order
• ids are more specific than classes
• classes are more specific than element names
• Style rules that directly target elements are more specific than style rules that
are inherited
• If elements have the same specificity, the later rule wins
<div> <div>
<strong>What color am I?</strong> <strong>What color am I?</strong>
</div> </div>
1. Values
The value of a CSS property can be: keyword, variable
Keyword:
• auto: The browser automatically calculates the value.
• inherit: The attribute will use the same value as the parent element.
• none: Remove previously assigned values.
• normal: Using the default value of an attribute
• transparent: Transparent, allowing one component to be seen through to the
components beneath it.
Variable: Numerical Values and Units
Fixed units like px (pixels), Responsive units like % (percentage of parent), etc.
2. Fonts
Property Description
font Setting all properties for font in one declaration
(font-style, font-variant, font-weight, font-size/line-height, font-family, etc.)
font-family A prioritized list of [generic] font family names for an element
font-size Sets the size of a font (absolute or relative), default: 16px/1em
font-style Sets the style (normal | italic | oblique) for a text
font-variant Specifies whether a text should be displayed in small-cap
(normal | small-caps)
font-weight Sets the thickness of a font
(normal | bold | bolder | lighter | number)
2. Fonts
Font Families:
font-family: specifies the font for an element : "Serif" hay "Times New Roman"
Types:
Generic family: used to refer to a group of font families that are very similar, such as :
"Serif" and "Monospace"
Font family: identify a specific font family such as: "Times New Roman" and "Arial"
2. Fonts (tt)
Font Families:
• should hold several font names as a "fallback" system
• Always start with the font you want, and always end with a generic
family
• Note: If the font name is more than one word, it must be in quotation
marks, like: "Times New Roman".
Example:
2. Fonts
CSS3 @font-face: This allows web browsers to use fonts not pre-installed
on the user's computer by directly downloading the necessary fonts from
the web server.
Syntax:
Example:
2. Fonts
Font Style:
font-style: specifies the font style for a text
VALUES : normal | italic | oblique
italic and oblique are quite similar, but oblique is less supported
Eample:
Font Size:
font-size: specify the size of the text/font
VALUE: <length> | <percentage-parents-font-size> | smaller | larger | xx-small | x-small
| small | medium | large | x-large | xx-large | inherit
Example:
2. Fonts
font-weight: specifies how thick or thin characters in text should be
displayed
VALUES: normal | bold | bolder | lighter | 100-900
Example:
3. Text
Property Value
color color-value (color name | rgb | rgba | hsl | hsla)
text-align left | right | center | justify
text-decoration line (none | underline | overline | line-through) color style (solid | double
| dotted | dashed | wavy)
text-indent length (fixed or relative)
text-justify auto | inter-word | inter-character | none
text-overflow clip | ellipsis | string (to represent the clipped text)
text-shadow h-shadow v-shadow [blur-radius] color (e.g. 2px 2px 1px black)
text-transform none | capitalize | uppercase | lowercase
3. Text
Text properties allow you to format a block of text, including: : color,
letter-spacing, word-spacing, line-height, white-space, text-align, vertical-
align, text-indent, text-decoration, text-transform
color :
VALUES: <color> | inherit
Example:
3. Text
word-spacing : specify the space between the words
VALUES: normal | <length> | inherit
Example:
3. Text
white-space : specifies how white-space inside an element is handled
VALUES: normal | pre | nowrap | pre-wrap | pre-line
Example:
3. Text
vertical-align : sets the vertical alignment of an element
VALUES: baseline | sub | super | top | text-top | middle | bottom | text-bottom |
<percentage-line-height>% | <length> | inherit
Example:
3. Text
text-decoration: control the appearance(line-through , underline , overline )
VALUES: none | line-through | underline | overline
Example:
4. Background
Property Value
background bg-color bg-image position/bg-size bg-repeat bg-origin
bg-clip bg-attachment
(e.g. background:url([Link]) 10px 20px/50px 50px;)
background-color color-value (color name | rgb | rgba | hsl | hsla)
background-image image-url
background-position position-name (e.g. left top | left center | etc.) |
x% y% (relative) | xpos ypos (absolute)
background-size auto (origin size) | length (width height) | cover | contain
background-repeat repeat | repeat-x | repeat-y | no-repeat
background-origin padding-box | border-box | content-box
background-clip Painting area: border-box | padding-box | content-box
background-attachment scroll (with the page), fixed, local (scroll with the element
CTU
49
ĐẠI HỌC CẦN THƠ
Cộng đồng – Toàn diện – Ưu việt content) Faculty of Computer Network and Communication
[Link] 49
• CSS Basic Properties
4. Background
background-color: property specifies the
background color
VALUES: <color> | transparent
4. Background
background-repeat: sets if/how a background image will be repeated. By
default, a background-image is repeated both vertically and horizontally
VALUES: repeat | repeat-x | repeat-y | no-repeat
Example:
4. Background
background-position: set the starting position of the background image.
By default, a background-image is placed at the top-left corner
VALUES: <length> | <percentage-box-width+padding>% | <left | right | center> <top |
bottom | center>
Example:
4. Background
background (shorthand property): specify all the background properties in
one single property
VALUES: <background-color> <background-image> <background-repeat>
<background-attachment> <background-position> | none
5. Position
position: controlling the placement of elements
VALUES: static | relative | absolute | fixed
• static: positioned static by default (not affected by top, bottom, left, right)
• relative: positioned relative to its normal position, top, bottom, left, right
properties will cause the element to be adjusted away from its normal
position
• absolute: positioned relative to the nearest positioned ancestor
• fixed: positioned relative to the viewport, it always stays in the same place
even if the page is scrolled
Note: An element with the position: relative, absolute, or fixed will have
the ability to overlay another element.
5. Position
Properties affect the position: <span id="e2">Element</span>
• top: Move the element a certain
distance from the top edge
• right: Move the element a certain
distance from the right edge
• bottom: Move the element a certain
distance from the bottom edge
• left: Move the element a certain
distance from the left edge
VALUES: auto | <length> |
<percentage-parents-width>%
5. Position
Example: <span id="e1">1</span>
<span id="e2">2</span>
<span id="e3">3</span>
#e2{
top:30px;
left:50px;
}
6. Table
Property Values
border border-width border-style border-color
border-width top right bottom left (name or value, e.g. thin medium thick 10px;)
border-style top right bottom left (none | hidden | dotted | dashed | solid | double
| groove | ridge | inset | outset)
border-color top right bottom left
border-collapse separate | collapse
border-spacing length | h-length v-length
caption-side top | bottom
empty-cell show | hide
table-layout auto (cells’ width belongs to the content) | fixed (equal column width if
the column width is not set; otherwise, uses the width of the 1st row)
ĐẠI HỌC CẦN THƠ [Link]
CTU
57 Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
57
• CSS Basic Properties
6. Table
border: specify the width, style, and color of table borders
6. Table
caption-side: caption position
VALUES: top | bottom
6. Tables
7. List
Used to create styles for list elements(<ul>, <ol>)
list-style-type: specifies the type of list-item marker in a list
VALUES: disc | circle | square | decimal | decimal-leading-zero | upper-roman | lower-
roman | upper-alpha | lower-alpha | lower-greek | none | inherit
Property Values
list-style list-style-type list-style-position list-style-image
list-style-type none | disc | circle | square | decimal | decimal-leading-zero |
lower-roman | upper-roman | lower-alpha | upper-alpha | etc.
list-style-position inside | outside
list-style-image none | url(…)
maker-offset auto | length
ĐẠI HỌC CẦN THƠ [Link]
CTU
61 Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
61
• CSS Basic Properties
7. List
list-style-image: replace the list-item marker with an image
VALUES: url( <url>) | none
7. Lists
8. Cursor
cursor: Set the shape for the cursor
VALUES: default | url(<url>) | auto | crosshair |
pointer | move | e-resize | ne-resize | nw-resize |
n-resize | se-resize | sw-resize | s-resize | w-
resize | text | wait | help | progress | inherit
9. CSS Units
Unit Description
% percentage
in inch
cm centimeter
mm millimeter
em 1em is equal to the current font size. 2em means 2 times the size of
the current font. E.g., if an element is displayed with a font of 12 pt,
then '2em' is 24 pt. The 'em' is a very useful unit in CSS, since it can
adapt automatically to the font that the reader uses
ex one ex is the x-height of a font (x-height is usually about half the
font-size)
pt point (1 pt is the same as 1/72 inch)
pc pica (1 pc is the same as 12 points)
px pixels (a dot on the computer screen)
ĐẠI HỌC CẦN THƠ [Link]
CTU
65 Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
65
Content
1. Introduction to CSS
2. CSS levels and syntax
3. CSS selectors
4. CSS properties
5. Inheritance
6. The layout
7. The Box model
8. CSS convention
Inheritance
CSS styles are inherited from parent to child
a, h1, p, strong {
Instead of selecting all elements font-family: Helvetica;
individually }
body {
font-family: Helvetica;
You can style the parent and the }
children will inherit the styles h2, h3 {
font-family: Consolas;
}
Exception in Inheritance
While many CSS styles are inherited from parent to child, not all CSS
properties are inherited
<a href="/home">
Back to <em>Home</em> <em> inherits the font-family
</a> property, but not the display
+
a {
display: block;
font-family: Arial;
}
There's no rule for what properties are inherited or not: the inheritance
behavior defined in the CSS specification
[Link]
ĐẠI HỌC CẦN THƠ [Link]
CTU
68 Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
68
• Inheritance
<h1>Chocolate</h1>
<p>
<a href="...">CSS</a> is wonderful
</p>
+
body {
color: red;
font-family: Helvetica;
}
a {
color: red;
}
Display
The ‘display’ property specifies how how element is displayed
Possible value: inline, block, list-item (same as block), etc.
Grouping Elements
Grouping elements lets us style multiple elements as a whole
Width and height properties can be used to resize the block and <img>
elements
Overflow
The content of an element may overflows
(bigger) its container
Possible values for these properties:
• visible: the overflow is not clipped and
rendered outside the element’s box
• hidden: the overflow is clipped, the rest
content is visible
• scroll: the overflow is clipped but a
scrollbar is added
• auto: if the overflow is clipped, a scrollbar
will be added
ĐẠI HỌC CẦN THƠ [Link]
CTU
77 Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
77
• The Layout
Overflow
The overflow, overflow-x, overflow-y properties are used to specify
what happens
Visibility
The ‘visibility’ property specifies whether an element is visible
VALUES: visible | hidden | collapse (used only with table row/column)
The ‘opacity’ property sets the opacity level for an element
VALUES: from 0.0 (fully transparent) to 1.0 (fully opaque)
Note that, hidden elements (set with display property) still take up space on
the page
Floating
The ‘float’ property is used to float boxes on the sides of other boxes and
the siblings will wrap around the floating element
VALUES:
• none (default): the element doesn’t float
• left: the element floats to the left of its container
• right: the element floats to the right of its container
Floating
The ‘clear’ property is used to specify
that an element should not wrap around
above floated elements
VALUES:
• none (wrap floating elements on both
sides),
• left (doesn’t wrap the left element),
• right (doesn’t wrap the right element),
• both (doesn’t wrap both left and right)
Floating
.box1 { .box2 {
background-color: lightgrey; background-color: lightgrey;
width: 200px; width: 200px;
border: 20px solid green; border: 10px solid green;
padding: 15px; padding: 5px;
margin: 20px; margin: 10px;
} }
width: 340px
height: 400px
width: 400px
ĐẠI HỌC CẦN THƠ [Link]
CTU
89 Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
89
• The Box Model
Coding Convention
A CSS rule can be written as follow:
selector { property: value; ... }
However, it is recommended to use the following style:
selector { /* Style the header */
property: value; .header {
... background-color: #f1f1f1;
} padding: 20px;
Using comments in CSS text-align: center;
}
is also recommended:
/* comment (multiple lines) */
Naming Convention
Class name or ID should describe the semantic, not format
Example: use warning instead of redbox
Resources
CSS tutorial:
[Link]
[Link]
[Link] SCSS basics
CSS references:
[Link]
[Link]
CSS tools:
[Link] CSS code generator
[Link]