Styling LWCs uses CSS as a web standard technology, so knowing the 2 base concepts and how they affect styling is crucial:
In CSS, some styles are inherited from the parent to the child while others are not, allowing to minimize the number of CSS rules used. You can check which properties are inherited on this page Full property table (w3.org)
Given the following HTML file, please notice how the p
element which has no style specified, it inherits the color from the parent div
, but not the border:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>title</title>
</head>
<style>
.parentclass {
color: red;
border: 5px solid green;
}
</style>
<body>
<div class="parentclass">
Starting the parent div
<p>
This is a child paragraph that inherits styling from the parent
</p>
Ending the parent div
</div>
</body>
</html>
<aside> ☝ Regarding inheritance and also relevant for LWC, notice that Inheritance is applied when there are no Cascading rules.
</aside>
CSS Cascading is the process of accumulating all the styles applicable to an HTML tag that are not inherited and when conflicts appear, the more specific prevails.
Given a tweaked version of the previous code, notice that:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>title</title>
</head>
<style>
.parentclass {
color: red;
border: 5px solid green;
font-style: italic;
}
p {
color: violet;
font-weight: bold;
}
p.second {
color: orange;
}
</style>
<body>
<div class="parentclass">
Starting the parent div
<p class="first">
This is the first paragraph witn inherited styling
</p>
<p class="second">
This is the second paragraph witn inherited styling
</p>
Ending parent div
</div>
</body>
</html>
Both paragraphs have the font in bold and italic, as this style is inherited from the parent.