Home > Mobile >  CSS - URL Import rewrites own styles
CSS - URL Import rewrites own styles

Time:03-07

In my vue project I'm using bootstrap (5.0) and a font from google fonts.

I noticed, that even though the import is written first in the screen.css file and the own style second that the import rewrites the own styles. when inspecting the h1 element the own style gets cancelled out and the font-weight: 500 comes from the bootstrap css file.

is there any way to ensure a sequential reading of the screen.css file?

@import url('https://fonts.googleapis.com/css2?family=Inter:wght@200;400;600;800&display=swap');
@import url('./bootstrap/bootstrap.min.css');

:root{
  --text-primary: rgb(17, 24, 39);
  --sans-serif: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
}

body{
  font-family: var(--sans-serif);
  color: var(--text-primary);
}

h1, h2, h3{
  font-family: var(--sans-serif);
  font-weight: 800;
}

enter image description here

CodePudding user response:

This is because .h1, .h2 and .h3 (class selectors) have higher specificity than h1, h2 and h3 (element selectors) respectively and if the same specificity is there, the CSS rule that came later will override the styles of the CSS rule that came earlier.

Examples

div, p {
    padding: 1em;
    /* This black border will not be applied */
    font-family: sans-serif;
}

/* The rule with `border: 0.1em solid red;` came later than the rule with `border 0.1em solid black` */

div {
    border: 0.1em solid black;
}

div {
   border: 0.1em solid red;
}

/* `.example` selector has higher specificity than `p` selector */

.example {
    background: #043240;
    color: white;
}

p {
    background: #202020;
}
<div>Example</div>

<p >Example</p>

CodePudding user response:

Class selectors (such as .h1) have higher weight/priority than tag selectors (such as h1).

If you give your rules the same or higher weight the rules will be read sequentially.

See https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

CodePudding user response:

Like previous answers, this is all a priority issue, if you can, define a new CSS file with more specific rule to match your h1 tag. For example you can surrond every h1 tag with a div with a new class.

<div class='title'>
  <h1>My title</h1>
</div>

<style>
.class h1
{
  font-weight : 500;
}
</style>

But if you want to bypass selector priority you can use !important keyword in a new CSS file.

Note that this is bad practice and you should always define a clean element architecture. https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity#the_!important_exception

  •  Tags:  
  • css
  • Related