1

I have a really weird situation where my view is different depending on where I put the following CSS class. I only have one item that is connected to this class which is my md-progress-bar from Angular Materials 2. I want it to float underneath my tool bar which is fixed on the screen.

.floating-progress {
  position: fixed;
  top: 0px;
  z-index: 1005;
}

When I put this inside app.component.css, I get the following result where the bar sits on the top of the tool bar.

screen shot 1

However, when I change this css class to my global styles.css, I get a the actual result that I wanted screen shot 2

How come there is a different depending on where I put it?

ErnieKev
  • 2,831
  • 5
  • 21
  • 35

1 Answers1

1

Angular does style encapsulation for styles added components.

The components get attributes like _ng_context-xxx with unique xxx added. The CSS selectors will be rewritten to match only these attributes, before the CSS is added to the DOM.

See also https://angular.io/docs/ts/latest/guide/component-styles.html

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Hmm. I am aware of such feature. However, how would this change the view? Does that mean everytime I want to do something simple like #someId { top: 20px; }, I will need to watch out whether I declare it at the lowest level or parent level? – ErnieKev Feb 17 '17 at 13:34
  • In software development you usually should always care where to put something ;-) Actually this is about limiting styles added to components to just affect this component and nothing else - which is generally considered a good thing. If you want to affect your whole page, just add the styles outside Angular. If you want to have styles that cross component boundaries, you can use `/deep/`. See also http://stackoverflow.com/questions/34542143/load-external-css-style-into-angular-2-component/34963135#34963135 – Günter Zöchbauer Feb 17 '17 at 13:38
  • Hi @Gunter. Thanks. I agree with that. However, I cant get my head around why there is a difference with this particular example. Shouldn't style really be not effected by where you put it. For example, if I want to set some item with id = "test" to have color blue, it shouldn't matter if I put it at the lowest level or the global style sheet (Though best practice would be lowest level). I just cant get my head around why, in this case, I get different result – ErnieKev Feb 17 '17 at 13:44
  • I don't know what to explain. You agree at first, but then you disagree. If you add styles to a component, then the style only affects this component. This is what style encapsulation is about. You can set `ViewEncapsulation.None` for each component to disable style encapsulation. – Günter Zöchbauer Feb 17 '17 at 13:48