Contents
  1. I. CSS Composite Selectors
  2. 1.1 Composite Selectors
  3. 1.2 Descendant Selectors
  4. 1.3 Child Selectors
  5. 1.4 Grouping Selectors
  6. 1.5 Pseudo-class Selectors
  7. 1.6 Composite Selector Summary
  8. II. CSS Element Display Modes
  9. 2.1 What Is an Element Display Mode?
  10. 2.2 Block Elements
  11. 2.3 Inline Elements
  12. 2.4 Inline-block Elements
  13. 2.5 Element Display Mode Summary
  14. 2.6 Converting Element Display Modes
  15. III. CSS Backgrounds
  16. 3.1 Background Color
  17. 3.2 Background Images
  18. 3.3 Background Tiling
  19. 3.4 Background Position
  20. 3.5 Background Attachment
  21. 3.6 Background Shorthand
  22. 3.7 Semi-transparent Background Colors
  23. 3.8 Background Summary
  24. IV. The Three Major Features of CSS
  25. 4.1 The Cascade
  26. 4.2 Inheritance
  27. 4.3 Specificity

I. CSS Composite Selectors

1.1 Composite Selectors

CSS classifies selectors by type as basic selectors and composite selectors. Composite selectors are built on basic selectors by combining them.

  • Composite selectors can select target tags more accurately and efficiently.

  • A composite selector consists of two or more basic selectors combined in different ways.

  • Common composite selectors include descendant selectors, child selectors, grouping selectors, pseudo-class selectors, and so on.

1.2 Descendant Selectors

A descendant selector, also known as a containment selector, can select child elements inside a parent element. Write the outer element first and the inner element second, with a space between them. When tags are nested, the inner tag becomes a descendant of the outer tag.

元素1 元素2 {属性1: 属性值1...}

The syntax above means: select all Element 2 elements inside Element 1. The following example selects all li tags inside a ul.

<!-- 例:选择ul里面所有li标签 -->
ul li { 样式声明 }
  • Element 2 can be a child or grandchild, as long as it is a descendant of Element 1.

  • Element 1 and Element 2 can be any basic selectors, for example, .nav li a {}.

1.3 Child Selectors

A child selector can select only the nearest-level elements within an element.

元素1>元素2 { 样式声明 }

The syntax above means: select all direct descendant Element 2 elements inside Element 1. The following example selects all nearest-level p tags inside a div.

<!-- 例:选择div里面所有最近一级p标签 -->
div>p { 样式声明 }

1.4 Grouping Selectors

A grouping selector can select multiple groups of tags and is commonly used for collective declarations.

In a grouping selector, the selectors are connected by an English comma “,”, and any type of selector can be part of a grouping selector.

Syntax:

元素1, 元素2 { 样式声明 }

The syntax above means select Element 1 and Element 2.

Example:

<!-- 选择u1和div标签元素 -->
u1, div { 样式声明 }

1.5 Pseudo-class Selectors

Pseudo-class selectors add special effects to certain selectors, such as adding special effects to links or selecting the 1st or nth element.

The most distinctive feature of pseudo-class selectors is that they use a **colon “:” for notation, such as :first-child and :hover.

There are many pseudo-class selectors, including link pseudo-classes and structural pseudo-classes.

(1) Link pseudo-class selectors

Link pseudo-class selectors are often used to change a link’s color or other styles when the mouse passes over it.

OptionPurpose
a:linkSelects all unvisited links
a:visitedSelects all visited links
a:hoverSelects links with the mouse pointer positioned over them
a:activeSelects active links (links pressed but not yet released)

Notes:

  • To ensure they take effect, declare them in LVHA order: link - visited - hover active.
  • Because links have default styles in browsers, they generally need explicitly defined styles in practice.

Example:

a {
	color: gray;
	text-decoration: none;
}

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

(2) The :focus pseudo-class selector

The :focus pseudo-class selector selects form elements that have received focus.

Focus means the cursor. Generally, only form elements such as <input> can receive it, so this selector is also mainly used for form elements.

input:focus {
	background-color: skyblue;
}

1.6 Composite Selector Summary

SelectorPurposeCharacteristicsUsageSeparator and usage
Descendant selectorSelects descendant elementsCan be a child or grandchildCommonThe symbol is a space, .nav a
Child selectorSelects nearest-level elementsSelects only childrenLess commonThe symbol is greater than, .nav>p
Grouping selectorSelects elements with the same stylesSupports group declarationsCommonThe symbol is a comma, .nav, .header
Link pseudo-class selectorSelects links in different statesRelated to linksCommonFocus on the practical a{} and a:hover syntax
:focus selectorSelects forms that receive the cursorRelated to formsLess commoninput:focus

II. CSS Element Display Modes

2.1 What Is an Element Display Mode?

Web pages contain many tags, and different types of tags are used in different places. Understanding their characteristics helps us lay out web pages more effectively.

An element’s display mode is the form in which the element (tag) is displayed. For example, a <div> occupies a line by itself, while multiple <span> elements can appear on one line.

HTML elements are generally divided into two types: block elements and inline elements.

2.2 Block Elements

Common block elements include <h1>~<h6>, <p>, <div>, <ul>, <ol>, and <li>. Among them, div is the most typical block element.

  • A block element occupies an entire line by itself.
  • Its height, width, margin, and padding can all be controlled.
  • Its width defaults to 100% of the parent container.
  • It is a container or box that can contain inline elements or block elements.

Note: Text elements cannot contain block-level elements. A <p> cannot contain block-level elements such as <div>. Similarly, <h1>~<h6> are text-based block-level tags and cannot contain other block-level elements either.

2.3 Inline Elements

Common inline elements include <a>, <strong>, <b>, <em>, <i>, <del>, <s>, <ins>, <u>, and <span>. Among them, <span> is the most typical inline element. Inline elements are also called inline-level elements in some contexts.

  • Adjacent inline elements appear on the same line, and one line can contain multiple inline elements.
  • Setting height and width directly has no effect.
  • The default width is the width of the element’s content.
  • Inline elements can contain only text or other inline elements.

Note: A link cannot contain another link, but in special cases, an a tag can contain a block-level element.

2.4 Inline-block Elements

There are several special tags among inline elements: <img>, <imput>, and <td>. They have characteristics of both block and inline elements.

  • They appear on the same line as adjacent inline or inline-block elements, but there are gaps between them, and multiple elements can be displayed on one line.
  • Their default width is the width of their content.
  • Their height, line height, margin, and padding can all be controlled.

2.5 Element Display Mode Summary

Element modeElement arrangementStyle settingsDefault widthContents
Block-level elementOnly one block-level element per lineWidth and height can be set100% of the containerCan contain any tag
Inline elementMultiple inline elements can appear per lineWidth and height cannot be set directlyWidth of its contentCan contain only inline elements
Inline-block elementMultiple inline-block elements per lineWidth and height can be set directlyWidth of its content

2.6 Converting Element Display Modes

In special cases, we need to convert an element’s display mode. Put simply, an element in one mode needs the characteristics of another mode.

For example, you may want to increase the clickable area of a link <a>.

Convert to a block element: display:block

Convert to an inline element: display:inline

Convert to an inline-block element: display:inline-block

Example:

a {
    width: 150px;
    height: 30px;
    background-color: skyblue;
    display: block;
}

III. CSS Backgrounds

CSS background properties can add background styles to elements on a page.

Background properties can set the background color, background image, background tiling, background image position, whether the background image is fixed, and so on.

3.1 Background Color

background-color sets the background color.

background-color: 颜色值

Color parameter: transparent (the default), or color.

3.2 Background Images

The background-image property describes an element’s background image. In real-world development, it is commonly used for logos, small decorative images, or very large background images. Its advantage is that the position is very easy to control.

background-image: none|url
Parameter valuePurpose
noneNo background (default)
urlSpecifies the background image using an absolute or relative address

Example:

div {
	width: 300px;
	height: 300px;
	background-image: url(images/background.jpg);
}

3.3 Background Tiling

background-repeat tiles a background image on an HTML page.

background-repeat: repeat | no-repeat | repeat-x | repeat-y
Parameter valuePurpose
repeatTiles the background image vertically and horizontally (default)
no-repeatDoes not tile the background image
repeat-xTiles the background image horizontally
repeat-yTiles the background image vertically

A page element can have both a background color and a background image; the background image is displayed on top.

3.4 Background Position

background-position changes the image’s position within the background.

background-position: x y;

The parameters are the x- and y-coordinates. You can use directional keywords or exact units.

Parameter valueDescription
lengthpercentage|a length value consisting of a floating-point number and unit identifier
positionDirectional keywords such as top|center|bottom|left|center|right

(1) Parameters are directional keywords

  • If both specified words are directional keywords, their order does not matter. For example, left top and top left have the same effect.
  • If only one directional keyword is specified and the other is omitted, the second defaults to center alignment.

(2) Parameters use exact units

  • If the parameter values are exact coordinates, the first must be the x-coordinate and the second must be the y-coordinate.
  • If only one numeric value is specified, it must refer to x, and the y-coordinate defaults to vertical centering.

(3) Parameters mix units

  • If the two specified values mix an exact unit with a directional keyword, the first value must be the x-coordinate and the second the y-coordinate.

3.5 Background Attachment

The background-attachment property sets whether a background image is fixed or scrolls with the corresponding area of the page. It can create a parallax scrolling effect.

background-attachment: scroll | fixed
ParameterPurpose
scrollWhether the background image scrolls with the object’s content (default)
fixedThe background image is fixed

3.6 Background Shorthand

To simplify background property code, we can combine these properties into the single background shorthand property, reducing the amount of code.

When using the shorthand property, there is no required order. The usual convention is:

background: background color background image URL background tiling background image scrolling background image position

Example:

background: transparent url(image.jpg) repeat-none fixed top center

3.7 Semi-transparent Background Colors

background: rgba(0, 0, 0, 0.3);

The four parameters are r, g, b, and alpha transparency, respectively. The final alpha transparency value ranges from 0~1, where 0 means fully transparent.

This property makes only the background color semi-transparent; the content inside is unaffected.

3.8 Background Summary

PropertyPurposeValue
background-colorBackground colorPredefined color value/hexadecimal /RGB code
background-imageBackground imageurl(image path)
background-repeatWhether to tilerepeat/no-repeat/repeat-x/repeat-y
background-positionBackground positionlength/position, representing the x- and y-coordinates respectively
background-attachmentBackground attachmentscroll for a scrolling background, fixed for a fixed background
Background shorthandReduces codeBackground color background image URL background tiling background image scrolling background image position
Semi-transparent background colorColor transparencybackground: rgba(0,0,0,0.3);

Background images are commonly used for small decorative images or very large background images in real-world development. Their advantage is that their position is very easy to control.

IV. The Three Major Features of CSS

CSS has three very important features: the cascade, inheritance, and specificity.

4.1 The Cascade

When the same selector sets the same style, one style overrides (cascades over) another conflicting style. The cascade mainly resolves style conflicts.

The principles of the cascade are:

  • When styles conflict, follow the proximity principle: the style closest to the structure is applied.
  • Styles that do not conflict do not cascade over one another.

4.2 Inheritance

Child tags inherit some styles from their parent tags, such as text color and font size.

For example, the following markup contains a p inside a div:

<div>
    <p>div内的p</p>
</div>

If styles are applied to the div at this point, the p tag also inherits those styles.

Inheritable styles include properties beginning with text-, font-, and line-, as well as the color property.

Line-height inheritance:

Line height can be specified with or without a unit.

body {
	font: 12px/1.5;
}
div {
	font-size: 14px;
}

Here, 1.5 represents 1.5 times the current element’s font size. Therefore, the line height in the div is 21px, while the default line height of other tags in the body is 18px.

4.3 Specificity

When multiple selectors target the same element, specificity comes into play.

  • If the selectors are the same, the cascade applies.
  • If the selectors are different, they are applied according to their selector weights.
SelectorSelector weight
Inheritance or universal selector *0,0,0,0
Element selector0,0,0,1
Class selector, pseudo-class selector0,0,1,0
ID selector0,1,0,0
Inline style style=""1,0,0,0
!importantMaximum
    <style>
        div {
            color: skyblue !important;
        }
        
        .test {
            color: greenyellow;
        }
        
        #demo {
            color: red;
        }
    </style>
</head>

<body>
    <div class="test" id="demo" style="color: pink;">hello world</div>
</body>

In short, the larger the scope, the lower the weight; the smaller the scope, the higher the weight.

Weight accumulation:

For composite selectors, weights are accumulated and must be calculated. The comments in the example below show the weight calculation for each selector:

/* ul内的li权重是0,0,0,1+0,0,0,1=0,0,0,2 */
ul li {
color: darkcyan;
}
/* li的权重是0,0,0,1 */
li {
color: skyblue;
}
/* .nav内的li权重是0,0,1,0+0,0,0,1=0,0,1,1 */
.nav li {
color: red;
}
  • Weights only accumulate; they do not carry over.
  • Weights are compared digit by digit from left to right.

This article references instructor Pink’s video tutorial from Heima Programmer. Heima Programmer instructor Pink’s introductory frontend video tutorial: https://www.bilibili.com/video/BV14J4114768