martin36
martin36

Reputation: 2363

Styling for CSS class not getting applied when class is added using Angular

I am trying to make a header that is localized under a div. When you scroll and the header reaches the top of the page it should "stay" there. I am using Angular so I found this solution: Bind class toggle to window scroll event here and I am using it for adding the class fix-header. In the inspector I can see that the class gets added but the styling does not apply when it is added. Here is my CSS for making the header fixed:

.wrapper {
  background-color: pink;
  height: 100px;
  z-index: 1;
}

.wrapper .fix-header{
  position: fixed;
  top: 10px;
}

The "fix-search" class is added here:

<body ng-app="myApp">
  <div ng-controller="MyController">
    <div class="banner">
      <div class="dummy-container"></div>
      <div class="wrapper" change-class-on-scroll offset="200" scroll-
           class="fix-header">
      </div>
    </div>
  </div>
 </body>

The line change-class-on-scroll offset="200" scroll-class="fix-header" adds the class fix-header to the wrapper div. Here is some working code: https://codepen.io/Martin36/pen/jmbEgJ

So my question is, why doesn't the class properties get applied when the class is added?

Upvotes: 1

Views: 1028

Answers (3)

nmg49
nmg49

Reputation: 1386

To elaborate on cnorthfield's answer:

/*Apply style to all elements of both the wrapper class and the fix-header class*/
.wrapper .fix-header
{

}

/*Apply style to all elements which have both the wrapper and fix-header classes*/
.wrapper.fix-header
{

}

Notice how the addition/removal of a single space significantly changes the meaning of the selector.

Upvotes: 0

martin36
martin36

Reputation: 2363

I incorporated the comment given by @Ronnie and the answer from @cnorthfield and made an updated pen: https://codepen.io/Martin36/pen/jmbEgJ, for those of you that are interested. The header now sticks to the top of the screen when the "dummy" div is scrolled past. The following changes were made:

/* Since the classes are on the same element there should not be a blank between them */
.wrapper.fix-header{
  background-color: pink;
  height: 100px;
  /* Without the "width" the header disappears */
  width: 100%;
  z-index: 1;
  position: fixed;
  top: 0;
  left: 0;
}

Upvotes: 0

cnorthfield
cnorthfield

Reputation: 3501

Why don't the styles get applied when the class is added?

Because you are referencing the wrong class, your CSS target should be:

.wrapper.fix-header{
  position: fixed;
  top: 10px;
}

Note no space between the wrapper class and the fix-header class

Upvotes: 1

Related Questions