user8827176
user8827176

Reputation:

How can I support different screen sizes with different stylesheets in Angular?

I am using Angular 5 and I am currently making a header, when I resize the screen to mobile resolution the design becomes very ugly. My idea was making two different stylesheets, one for mobile and one for PC like so:

<link rel="stylesheet" media="screen and (min-device-width: 800px)" href="800.css" />

Is this a smart way to resolve the issue? If not, please give me an alternative.

Besides this, where do I put the stylesheet link in Angular? Normally it is put in the index.html but in Angular styles are listed in the component.ts file, here i can not do the media="screen and (min-device-width: 800px)" part, so again, how can i resolve this?

Upvotes: 0

Views: 4932

Answers (2)

Ovidiu Mihota
Ovidiu Mihota

Reputation: 57

If i got it right you want to load only the needed css for mobile instead of loading all of it ( desktop one too ) , right ? If it is so , you have to define a script in your index.html

<script>
    var deviceWidth = window.orientation == 0 ? window.screen.width : window.screen.height;
    //use this if you want to check it is really a mobile device.
    var isAndroid = navigator.userAgent.indexOf('Android') >= 0 && window.devicePixelRatio;

    var cssHref = deviceWidth > 800 ? "app_desktop.css" : "app_mobile.css";
    var linkElement = document.createElement("link");
    linkElement.setAttribute("rel",  "stylesheet");
    linkElement.setAttribute("type",  "text/css");
    linkElement.setAttribute("href",  cssHref);
<script>

This wont be responsive it will work only once . It is also not tested so it wont work as expected :)

Upvotes: 0

Brampage
Brampage

Reputation: 6954

In your .angular-cli.json file you should add a string to apps.styles array.

For example when your mobile.css and tablet.css resides inside the app folder just add: mobile.css and tablet.css.
When the styles reside inside for example a styles folder (inside app), add: styles/yourstyle.css

Corresponding to your css file you add the media queries.

@media only screen and (max-width: 500px) {
    body {
        background-color: lightblue;
    }
}

You don't need to add the style links inside the index.html.

Upvotes: 2

Related Questions