Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load different CSS rule depending on the browser in an Angular 4 component

Tags:

css

angular

I have an Angular 4 application that looks quite different depending on the browser you use. This is an example of how it looks on Firefox 58 (and it's the way I want it to look):

App on Firefox 58

And this is an example of how it looks on Chrome 63:

App on Chrome

I opened a question a few days ago to see if I could fix this issue (Different 'div' heights in Chrome and Firefox) but I couldn't find a way to make it work for both browsers.

So, I'm thinking on loading a different CSS class depending on the user using Chrome or Firefox. Does Angular 4+ have a way of finding out the browser? What I would do then is to load the appropriate class using ngClass in the component's template that would, hopefully, fix the issue.

Or is there a better alternative?

Thanks in advance,

like image 510
Fel Avatar asked Jan 29 '18 15:01

Fel


2 Answers

Doing some more research, I found the solution in this article:

https://www.codeproject.com/Tips/1167666/How-to-Apply-CSS-HACKS-for-Different-Browsers-Chro

In my case, this is the solution I used:

/* Style only for Google Chrome/Opera */
@media screen and (-webkit-min-device-pixel-ratio:0) {
  td {
    height: 1px;
    vertical-align: top;
  }
}

/* Style only for Mozilla Firefox */
@-moz-document url-prefix() {
  td {
    height: 100%;
    vertical-align: top;
  }
}

/* Style only for Internet Explorer */ 
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
  td {
    height: 100%;
    vertical-align: top;
  }
}

Thanks for all the suggestions!

like image 66
Fel Avatar answered Sep 18 '22 12:09

Fel


per the OP's question, yes you can detect browser (user agent) types by using window.navigator.userAgent. Learn more about it at mozilla

a rough function could look like:

getBrowser() {
  if (window.navigator.userAgent.indexOf('Mozzila') != -1) {
      this.firefox = true;
  else {
      this.firefox = false;
  }
}

This will return browser specifications. Put this function in a service and you can call it during the ngOnInit hook in angular. Then you can dynamically add a css stylesheet you have created by adding it to the DOM

<link *ngIf="!firefox" rel="stylesheet" href="path/to/css">

alternately, you could create the style tag and append it to the DOM on the fly.

You could just use it for a single style in the css stylesheet like this:

<div class="title" [class.chrome]="!firefox">

that sounds like a really bad idea

@powerbuoy is right, this is a bad idea. Not in function, but in how you want to put it into practice. This is not a very scalable method and will not work across many browsers. Other (better) css solutions include using flexbox or bootstrap

like image 42
FussinHussin Avatar answered Sep 19 '22 12:09

FussinHussin