0

For example:

<div className="container col-md-3 thisstyle">

Which className takes precendence in reactjs?

tacoshy
  • 3,056
  • 2
  • 7
  • 21
coding3344
  • 13
  • 2
  • 2
    https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity – dave May 25 '21 at 18:17
  • 2
    `className` is just the elements regular `class`. Any rules that apply to `class` with respect CSS and specificity apply to `className`. My naive guess is that React just didn't want to have a keyword like "class" strewn about when referring to an element's `class` attribute. – zero298 May 25 '21 at 18:21
  • ReactJS has nothing to do with precedence of CSS classes. Also, the question of precedence in CSS is not applied to classes, but to every single rule. You can have multiple classes on an element, each of which will contribute its rules. If there is a conflict, the specificity is checked; see the comment by @dave. – orithena May 25 '21 at 18:22

2 Answers2

-2

CSS works with selectors specifity. An ID selector has higher specificity than a class selector which has a higher specificity than a tag selector, etc...

Your question is incomplete. It depends on the actual selector that applies styles on the element.

Now if you have two selectors that have the same specificity (e.g: .container and .thisstyle), the one defined later in the stylesheet takes precedence, which could lead to inconsistent behaviors, so it's highly advised not to have same specificity selectors that override each other's CSS properties.

Guerric P
  • 20,579
  • 2
  • 28
  • 66
  • Actually in this case as illustrated it has more to do with the order of the rules in the CSS source files, the later rules will overwrite settings from earlier rules, regardless of the order of the rule references in the HTML. – Martin May 25 '21 at 19:04
  • Yes this it what I wanted to write, is it unclear? – Guerric P May 25 '21 at 19:19
-2

The className attribute works the same as the class attribute on traditional dom, and follows the same CSS precedence rules. In this case, it depends on the order in which they were declared in the source css files. If they were declared in different files, then the one that was imported last would take precedence.

https://css-tricks.com/the-order-of-css-classes-in-html-doesnt-matter/

In the end, className will "compile" to class when on the dom. The only reason it's named differently is because JSX is essentially JavaScript, and in JS, class is a reserved keyword.

qaismakani
  • 371
  • 1
  • 7