We usually want to ensure a consistent UI across browsers without having to constantly overwrite default styles. We can …
We already saw that inline styles overrule other styles. We've also seen, that we can apply multiple rules to the same element.
This begs the question:
What are the rules to resolve conflicting styles?
Specificity is the means by which browsers decide which CSS property value will be applied. It's a weight determined by the used selector.
Different selector types ordered by increasing weight:
The weight can be represented in this format: id-class-tag.
div.banner li /* 0-1-2 */
#upload > button /* 1-0-1 */
form [type="password"] /* 0-1-1 */
:root #myApp input:required /* 1-2-1 */
Weights get compared from left to right. Which means:
.banner /* 0-1-0 */
beats
body section div ul li /* 0-0-5 */
IntelliJ shows specificity in CSS if you hover over the selector.
Otherwise, these websites (among many) could help you analyse/calculate the specificity of your selector:
Inheritance controls what value is applied if none is explicitly specified for the property of an element.
There's two type of properties:
When specified, these properties' values are applied as default for all child elements.
Typical examples are text related properties like:
Specifying values for these properties will only apply them to the targeted elements.
Typical examples are layout related properties like:
Content: The actual content of the box, in which text, images and other child elements appear. Child elements are bound by this area.
Padding: Clears an area around the content, separating content and border. The padding is transparent.
Border: A border that goes around the padding and content. Backgrounds extend to the edge of this area/box. The border can be colored.
Margin: Clears an area outside the border to separate the element from its neighbors. The margin is transparent.
There are 2 ways to determine the size of a box from height and width values:
Default behaviour. The element's size (height, width) corresponds with the content box size. Padding and border add to the rendered width.
Includes padding and border into the values for an element's height and width. Increasing padding or border sizes will shrink the content box. Generally easier to use.
box-sizing: content-box | border-box;
.parent {
width: 250px;
background: lightskyblue;
}
.content-box {
box-sizing: content-box;
width: 100%;
padding: 5px;
border: solid #666 10px;
}
.border-box {
box-sizing: border-box;
width: 100%;
padding: 5px;
border: solid #666 10px;
}
The position property determines where the element is rendered:
Vertical margins (top and bottom) of blocks are collapsed in 3 cases.
When there's no border, padding or content between outer and inner margin.
Top and bottom margin collapses on blocks with zero height and no border or padding.
How can we avoid collapsing issues?
When should I use which one?