CSS Spacing
<% tp.file.cursor(2) %>
CSS Spacing
Summary
- Cách sử dụng
padding/margin/gap/để tạo space trong/ngoài/giữa các phần tử với nhau. - Ảnh hưởng của chúng khi dùng kèm với
position
Spacing
br, hrtag
Margin

- Nếu chỉ định 2 tham số:
margin: 100px 200pxthì sẽ làtop/bottom - left/right - Nếu chỉ định 3 tham số:
margin: 100px 200px 150pxthì sẽ theo ngược chiều kim đồng hồ: top - left - bottom. (right sẽ lấy theo left) - Có thể sử dụng
margin: 0 auto - Negative margin: set
margin-top: -20pxđể overlap elements bên trên. - Margin Collapse
- “Margin collapse works by selecting the largest value of two adjoining elements with vertical margin set on the adjoining sides.”
- Margin sẽ không cộng dồn vào. 2 phần tử cạnh nhau: 1 thằng margin-bottom: 50px, 1 thằng margin-top: 20px. Thì 2 thằng này sẽ cách nhau 50px, chứ không phải cộng dồn vào là 70px.
- Margin collapsing chỉ xảy ra với block margin chứ không phải với inline-margin.
- Muốn không bị ảnh hưởng bởi margin collapsing thì cần sử dụng
position: absolute, hoặc sử dụngfloat.
Padding
- Để tính toán size của box cho chuẩn thì ta nên sử dụng
box-sizing: border-box.- Ví dụ: Nếu element có padding: 30px, và width: 320px. Khi
box-sizing: content-box, value của box sẽ là: 320 + 30 * 2 = 380px. - Nếu sử dụng
boxsizing: border-boxthì box sẽ có giá trị = đúng 320 px
- Ví dụ: Nếu element có padding: 30px, và width: 320px. Khi
Positioning
- Các
positioncho phép ta add space elements vớitop, right, bottom, left, tuy nhiên, mỗi loại position lại control khác nhau:- An element with
position: relativewill maintain its place in the document flow, even when you set these values. They will be relative to your element’s position too. - An element with
position: absolutewill base the directional values from the relative parent’s position. - An element with
position: fixedwill base the directional values on the viewport. - An element with
position: stickywill only apply the directional values when it is in its docked/stuck state.
- An element with
Grid and flexbox
gap,row-grap,column-gap