Styling with CSS
| English | Chinese | Pinyin |
|---|---|---|
| CSS | 层叠样式表 | céng dié yàng shì biǎo |
| selector | 选择器 | xuǎn zé qì |
| declaration | 声明 | shēng míng |
| the box model | 盒模型 | hé mó xíng |
| padding | 内边距 | nèi biān jù |
| border | 边框 | biān kuāng |
| margin | 外边距 | wài biān jù |
| responsive design | 响应式设计 | xiǎng yìng shì shè jì |
| media query | 媒体查询 | méi tǐ chá xún |
One file decides how every page looks
- Change the heading colour in one CSS file and every page changes. That is the whole reason for keeping style out of the HTML.
- CSS 层叠样式表 selects elements and sets properties on them.
- A selector 选择器 chooses what to style; a declaration 声明 sets a property to a value.
In one sentence, say why style belongs in CSS rather than in the HTML.
Example: "One rule in the stylesheet changes every page at once, so the site can be restyled without touching the content."
The box model
- The box model 盒模型 is what every element actually is: content, then padding 内边距, then border 边框, then margin 外边距.
- Padding is inside the border and takes the background; margin is outside it and does not.
- ⚠ Most "why is this not lining up" trouble is a margin where padding was meant, or the reverse.
Put the parts of the box model in order from the inside out.
Padding is inside the border and takes the background; margin is outside it and does not.
Responsive design
- Responsive design 响应式设计 makes one page work on a phone and a laptop.
- Design the flexible case first: percentage or
max-widthrather than a fixed pixel width. - A media query 媒体查询 then handles the change a small screen genuinely needs, such as stacking two columns into one.
A card that overflows on a phone.
The wrong fix: width: 400px becomes width: 300px. Now it is wrong on both.
The right fix: max-width: 400px with width: 100%. The card is never wider than its screen and never wider than 400px, and no media query is needed at all.
The flexible rule handles every width. The media query is for the layout that must genuinely differ, not for patching a fixed size.
A card is too wide on a phone. What is the better fix?
The flexible rule covers every width at once, so no media query is needed for this at all.
Specificity decides which rule wins, not the order you wrote them in. An id beats a class, a class beats an element. When a style "does not apply", it is almost always losing to a more specific rule somewhere else.
Your style "does not apply". What is the most likely cause?
Specificity, not source order, decides. An id beats a class, a class beats an element.
Avoid !important. It wins by breaking the cascade rather than by being right, and every later fix then needs its own !important. A stylesheet that has three of them is on its way to having thirty.
Adding !important is a good way to make a stubborn style work.
It wins by breaking the cascade, so every later fix needs one too. Find the rule beating yours instead.