Reputation: 159
I am new at web development and I faced the confusion with certain styles not being applied at certain viewport size. So, what I wanted to apply is the font size to all elements inside the container, that is, as you can see in the code below:
Html
<div class="nav-container">
<h1><span class="buy">Buy</span>Books<span class="books">Books</span></h1>
<nav class="navbar" style="margin:0;">
<ul class="links" style="margin:0;">
<li><b><a href="#"> Home</a></b></li>
<li><a href=""> <b>Category</b></a></li>
<li><a href=""> <b>Books</b></a></li>
</ul>
</nav>
<div class="cart"><a href=""> <i class="fas fa-shopping-cart fa-2x"></i></a></div>
</div>
CSS
@media (max-width:1200px){
html{
font-size:1.4rem;
}
.nav-container {
font-size: 1rem;
}
}
But this works
@media (max-width:1200px){
.nav-container h1 {
font-size: 1rem;
}
}
As you can see the media query, if I target container it does not work but if I target specific element in that container it works ok. Why is that? The same issue with html in that media query which also is not applied. Please help I am a bit confused.
Upvotes: 0
Views: 64
Reputation: 720
It is because rem values are relative to the root html element, not to the parent element. That is, If font-size of the root element is 16px then 1 rem = 16px for all elements. If font-size is not explicitly defined in root element then 1rem will be equal to the default font-size provided by the browser (usually 16px).
In your second css you are giving to the h1 higher priority and you are rewriting the user agent stylesheet - Default browser settings.
Upvotes: 3
Reputation: 913
This is because of something called the "user agent stylesheet". This contains all of the default styles for your browser. In the case of the h1
element, you can see the default styles here.
The reason the first style isn't being applied is because you're relying on inheritance. Most elements will inherit inherit styles from their parents. Since the font-size
for h1
elements been specified in the user agent style sheet, it won't inherit the font-size
.
The second style is applied because it has higher specificity than the user agent style. You can read about css selector specificity here. You could also override the style of h1
elements by using the following declaration:
h1 {
font-size: 1rem;
}
This would be applied because it was declared later than the user agent styles, so the browser prefers it.
Upvotes: 1