# Web Learning - CSS

> This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to [original Chinese version](<https://blog.wendain.ing/posts/web-learn-css/>). I am continuously working to improve the translation.

主要参考了：

- [What is CSS? - Learn Web Development | MDN](https://developer.mozilla.org/zh-CN/docs/Learn_web_development/Core/Styling_basics/What_is_CSS)

# What is CSS

I've mentioned this in previous blog posts, so I won't repeat it here.

Below are some miscellaneous notes:

**Browser default styles**: If there is only HTML without CSS, the HTML file rendered by the browser uses the browser's default CSS styles.

Add code like this in the `<head>` block to import an external CSS file:

```html
<link rel="stylesheet" href="styles.css" />
```

# CSS Selectors

## Using Class Names

For example

```html
<ul>
  <li>项目一</li>
  <li class="special">项目二</li>
  <li>项目 <em>三</em></li>
</ul>
```

Then write in the CSS:

```css
.special {
    color: orange;
}
```

This will apply to all elements with the class name `special`. If you want it to only apply to `<li>` elements, you can change the `.special` above to `li.special`.

## Styling Based on State

The following CSS code makes unvisited links turn pink and visited links turn green:

```css
a:link {
  color: pink;
}

a:visited {
  color: green;
}
```

This will be covered in detail later in the section on pseudo-classes and pseudo-elements.

## Selector Lists

```css
h1,
.special {
  color: blue;
}
```

Just separate them with commas like this.

When using a selector list, if any selector is invalid (contains a syntax error), then **the entire rule will be ignored**.

## Types of Selectors

### Type, Class, and ID Selectors

Type:

```css
h1 {
}
```

Class:

```css
.box {
}
```

ID selector:

```css
#unique {
}
```

There are some others as well, which will be introduced later:

# Attribute Selectors

## Presence and Value Selectors

This syntax selects only `<a>` elements that have a `title` attribute:

```css
a[title] {
}
```

This syntax also restricts the attribute to a specific value:

```css
a[href="https://example.com"] {
}
```

 Matching elements that have `a` among a series of values:

```css
li[class~="a"] {
  color: red;
}
```

As for a series of values, they are separated by spaces; for example, `class="a b c d"` will be selected by `class~="a"`.

## Substring Matching Selectors

Just as the name suggests; you can look up the specific APIs yourself. Here's an example:

> If you have `box-warning` and `box-error` classes and want to match every element whose class starts with the string "box-", you can use `[class^="box-"]` to select both of them.

This mainly depends on the symbol:

- `^=` matches the beginning
- `$=` matches the end
- `*=` matches if it appears anywhere

You can also add some parameters to make the matching case-insensitive; look up the APIs yourself.

# Pseudo-classes and Pseudo-elements

- Pseudo-classes: used to define **special states** of elements. They don't change the HTML structure, but apply styles based on user behavior or specific document logic, starting with `:`
- Pseudo-elements are used to create **"fictional" elements that don't exist in the HTML document tree**, or to style specific parts of an element. It's as if CSS automatically generates extra HTML tags for you, starting with `::`

For example, the `:hover` pseudo-class selects an element when the mouse pointer hovers over it:

```css
a:hover {
}
```

Meanwhile, the `::first-line` pseudo-element selects the first line of an element:

```css
p::first-line {
}
```

Other commonly used pseudo-classes include:

- `:first-child`
- `:last-child`
- `:only-child`
- `:focus`

You can combine pseudo-classes and pseudo-elements:

```css
article p:first-child::first-line {
  font-size: 120%;
  font-weight: bold;
}
```

This selects the first line of the first `<p>` element inside a `<article>` element.

There is a very useful category of pseudo-elements: `::before` and `::after`, which are a way to insert content into the document using CSS:

```html
<p class="box">我的 HTML 页面的盒子中的内容。</p>
```

```css
.box::before {
    content: " ➥"
}
```

# Combinators (Relational Selectors)

## Descendant Combinator

The **descendant combinator** typically combines two selectors with a single space (` `) character, and is mainly used for text with a parent-element relationship.

For example, if we only want to apply our special style to `<em>` elements inside `<li>` elements, we can write it like this — this kind of selector is called the **descendant selector**:

```css
li em {
  color: rebeccapurple;
}
```

## Child Combinator

Using `>`, it only matches when the selector targets direct child elements (first-level ones); more distant descendants in the inheritance hierarchy do not match.

```css
article > p
```

## Adjacent Sibling

If you want to **precisely target the single element immediately following a certain element** and apply styles, use the **adjacent sibling combinator**:

```css
h1 + p {
	font-size: 200%;	
}
```

This way, the **single** `<p>` **immediately** following every `<h1>` will have this style applied.

## General Sibling

If you want to match **all** elements following a certain element, use the general sibling combinator `~`:

```css
h1 ~ p {
  font-weight: bold;
  background-color: #333;
  color: #fff;
  padding: 0.5em;
}
```

All `p` elements after `h1` will be selected and styled.

## Using Combinators

They can be combined together:

```css
/* selects any <span> that is inside a <p>, which is inside an <article>  */
article p span { ... }

/* selects any <p> that comes directly after a <ul>, which comes directly after an <h1>  */
h1 + ul + p { ... }
```

The following code will style elements with the class name `special` that are inside a `<p>` immediately following a `<h1>`, within the `<body>`:

```css
body h1 + p .special {
}
```

Or select list items with the class `a` among the direct children of a `<ul>`:

```css
ul > li[class="a"] {
}
```

# The Box Model

Boxes are generally divided into:

- Block boxes
- Inline boxes

There are also two types:

- Inner display
- Outer display

## Outer Display Types

Boxes with the `block` outer display type exhibit the following behaviors:

- The box will break onto a new line
- It has `width` and `height`
- Padding, margin, and border will "push away" other elements from around the current box

Boxes with the `inline` outer display type exhibit the following behaviors:

- No line break
- No `width` and `height`
- Vertical padding, margin, and border are applied but **do not** push away other boxes in `inline` state; horizontal ones **do** push away other such boxes.

A simple example: `div` uses `block` as its outer display type; `span` uses `inline` as its outer display type.

## Inner Display Types

The inner display type determines how elements inside the box are laid out.

Changing the value of the `display` property can change whether the box's outer display type is block or inline.

## What is the CSS Box Model?

![Box model diagram](https://image.wendaining.top/box-model.png)

- Content box: the area that displays content, sized using `inline-size`, `block-size`, `width`, `height`, etc.
- Padding box: sized using `padding`
- Border box: sized using `border`
- Margin box: the outermost layer, serving as the whitespace between this box and other elements, sized using `margin`

### The Standard CSS Box Model

An example:

```css
.box {
  width: 350px;
  height: 150px;
  margin: 10px;
  padding: 25px;
  border: 5px solid black;
}
```

### The Alternative CSS Box Model

Simply put, `width` and `height` don't define the size of the content area, but the size of the entire box (excluding margin, of course); the size of the content area is derived from the total size minus the border and padding.

To use the alternative box model for all elements, set it like this:

```css
html {
  box-sizing: border-box;
}

*,
*::before,
*::after {
  box-sizing: inherit;
}
```

## Setting Margins, Padding, and Borders in Detail

### Margin

- Margin is the invisible space around the box.
- It pushes other elements away from the box.
- Margin values can be positive or negative.
    - Setting a negative value on one side of the box will cause the box to overlap with other content on the page.
- Whether using the standard model or the alternative model, margin is always added on top of the visible portion after it's calculated.

You can control it all at once with `margin`, or control each side separately using

- `margin-top`
- `margin-right`
- `margin-bottom`
- `margin-left`

### Border

There are many properties that can be set; check the API for details; the settings for the four sides are similar to `margin`.

### Padding

There are many properties that can be set; check the API for details; the settings for the four sides are similar to `margin`.

## `display: inline-block`

A special position between `inline` and `block`.

It achieves some of the block-level effects we need:

- Setting `width` and `height` properties will take effect.
- `padding`, `margin`, and `border` will push away other elements
- No line break

# Cascade, Specificity, and Inheritance

## Conflict Rules

### The Cascade

When two rules of the same level are applied to an element, the one **written later** is the rule actually used.

## Understanding Inheritance

For example, a `<ul>` wrapped with several layers of `<ul>` and `<ol>`.

Suppose the outermost one is `<ul class="special">`, and the CSS sets some `color` properties for this `.special`,

Since `color` is inheritable, the nested children will also inherit this color.

Not all properties can be inherited; for example, `width`, `margin`, etc. are not.

### Controlling Inheritance

There are five special property values that every CSS property accepts:

- `inherit`: enables inheritance, same as the parent property
- `initial`: the initial value
- `revert`: resets to the browser's default style, rather than the default value applied to the property
- `revert-layer`: the property value applied to the selected element is reset to the value established in the previous cascade layer
- `unset`: if the property is naturally inherited, it acts like `inherit`; otherwise it acts like `initial`

### Resetting All Property Values

Use the `all` property, which is a convenient way to set a series of inheritable properties

```css
blockquote {
  background-color: orange;
  border: 2px solid blue;
}

.fix-this {
  all: unset;
}
```

## Understanding the Cascade

The cascade is what happens when an element corresponds to multiple CSS styles (for example, being selected by both a class selector and a universal selector at the same time) — **the style to apply is chosen according to the order of specificity**.

The main rules are:

1. **Style origin** (priority of styles from different origins)
2. **Selector specificity** (different types of selectors have different weights)
3. **Order of appearance** (later rules override earlier rules)

> [!IMPORTANT]
>
> The specificity order only applies to a single property. For example, for a certain element, if "bold, green color" and "red color" are set at the same time, then comparing specificity only applies to the "color" property; "bold" has no conflict and will be applied directly.

### Style Origins

Browser default styles < External CSS < Internal CSS < Inline CSS < `!important`

### Selector Specificity

The rules are as follows:

| Selector Type | Example | Weight |
| :------------: | :----------------------: | :-------: |
| Universal selector | `* {}` | 0 |
| Element selector | `div`, `p`, `h1` | 1 |
| Class selector, pseudo-class | `.main`, `:hover` | 10 |
| ID selector | `#header` | 100 |
| Inline style | `style="color: blue;"` | 1000 |
| `!important` | `color: red !important;` | ∞ (highest) |

> [!NOTE]
>
> The only way to override `!important` is with another `!important` that has the same *specificity* and appears later, or with higher specificity.

### Order of Appearance

No explanation needed

# Closing Thoughts

Reading too much of this doesn't seem very interesting; most of the rest is rather trivial syntax. Knowing the core concepts feels sufficient for someone like me who's just reading about frontend for fun.

However, there are still a few topics that feel somewhat useful, so I'll list them as TODOs:

- Basic text and font styling (mainly the font settings part)
- Floats
- Positioning
