初學時Margin、Padding傻傻分不清楚,心想反正畫面有就好了,被問了『你何時用Margin?何時用Padding?』,於是針對這個議題展開了追尋。這裡會談一下box-model以及Margin與Collapsing margins(外距折疊)並談一些Padding。
以上為Udemy Advanced CSS and Sass提到Box Modle,在此引用。
規範節錄重點摘要:
這裡我就不付上原文,有興趣可以前往8.1 Box dimensions探險。
.card {
margin: 1px 1px 1px 1px (上左下右)
margin: 1px 1px 1px (上 左右 下)
margin: 1px 1px (上下 左右)
}
- Margin properties specify the width of the margin area of a box.
- The 'margin' shorthand property sets the margin for all four sides while the other margin properties only set their respective side.
- These properties apply to all elements, but vertical margins will not have any effect on non-replaced inline elements.
- Negative values for margin properties are allowed, but there may be implementation-specific limits.
簡單總結一下:
名詞解釋補充
替換內聯元素(replaced inline elements) :
<img>
(顯示影像)、<audio>
(播放音訊)、<video>
(播放影片)等。非替換的內聯元素(non-replaced inline elements)
<span>
、<a>
、<strong>
、<em>
。什麼是塌陷呢?又叫做折疊?起初我剛遇到這問題的時候,也是what happen?滿臉問號。簡單來說就是, 『Margin比大小』,當兩個以上Margin相遇,大的會吃掉小的。讓我們來看看規範大人怎樣說這件事呢?
- In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin.
- Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.
但是它有例外啦!
Adjoining vertical margins collapse, except:
- Margins of the root element's box do not collapse.
- If the top and bottom margins of an element with clearance are adjoining, its margins collapse with the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block.
- If the top margin of a box with non-zero computed 'min-height' and 'auto' computed 'height' collapses with the bottom margin of its last in-flow child, then the child's bottom margin does not collapse with the parent's bottom margin.
簡單總結一下,
- Unlike margin properties, values for padding values cannot be negative. Like margin properties, percentage values for padding properties refer to the width of the generated box's containing block.
以下是目前自己的一些想法
最新規範參考:
CSS Box Model Module Level 3