0

What I am trying to do is create default css styles that when I combine multiple classes together I want to override some of the default styles from another class. Here is an example of what I am trying to do.

style.css

.navBar {
  position:absolute;
  left:0px;
  right:0px;
  width:100%;
  height:50px;
  background-color: #333333;
}
.fixed {
  position: fixed;
}
.top {
   top:0px;
}
.left {
  float:left;
  left:0px;
}   
.navBar .left {
  width: 50px;
  height:100%;
}

In my html if I have <div class="navBar"> then it will just use the styles in .navBar but when I try to do <div class="navBar left"> I want it to override the width and height of .navBar but keep everything else from .navBar and .left

I dont want to put the height and width inside .left because I want to keep it as universal as possible.

Juan Sierra
  • 261
  • 2
  • 13

3 Answers3

4

Use the CSS selector .navBar.left. This checks for any elements with a class of navBar that also have a class of left. Currently you are using .navBar .left. Instead of checking if an element has both classes, it checks for all elements with class left that are children of navBar

Neil A.
  • 841
  • 7
  • 23
1

You probably shouldn't have specific classes like .fixed and .top like that. I'd suggest you to imagine a base class for something you want to style (ie.: your navBar) and than add other classes to modify them (like left). Read a bit about BEM (block, element, modifier) or any other method to make your CSS more modular and try to slowly apply that to your CSS.

You can always stack classes to make them more specific (take priority), like .navBar.left or use !important on super specific classes like those that only set one property, but use any of these techniques too much and your CSS will soon become unstable and super hard to maintain.

Learn how to better structure and organize your CSS. It will pay off!

rafaelbiten
  • 6,074
  • 2
  • 31
  • 36
0

First of all, Do NOT write classes names in camelCase style, it's not meant for css ,see why.

This is an example of applying and extending the default style by adding multiple classes, click on Run Code snipped to see it in action

html, body{
  margin: 0;
}
.nav-bar {
  position:absolute;
  top: 100px;
  width:100%;
  height:50px;
  background-color: #AC92EC;
  text-align: center;
}
.fixed {
  position: fixed;
  background-color: #A0D467;
}
.top {
   top:0;
}
.left {
  left:0;
   width: 200px;
  background: #48cfad;
}
<div class="nav-bar">
  defualt navbar  
</div>

<div class="nav-bar left">
  left navbar
  </div>

<div class="nav-bar fixed top">
  fixed and top navbar
</div>
Community
  • 1
  • 1
Murhaf Sousli
  • 12,622
  • 20
  • 119
  • 185