Different CSS Stylesheet for Routes

Different css stylesheet for routes

I recommend to use the following file structure and pattern:

- components
- Main.js
- Utility
- index.js
- styles.scss
- pages
- HomePage
- index.js
- styles.scss

Then specify the component related styles within the component's stylesheet, and the page-realated styles within the page's stylesheet. And use pages for routes, not components.
Finally, wrap every component into a specific class selector, and add wrap the belonging sass file into that selector (like .home-page).
For this reason, please, use sass instead of css, because you can embed style definitions within each other and use the top one as a "namespace". So the styles will not affect to each other.

// Main.js
import HomePage from '../pages/HomePage';

<Switch>
<Route path="/" exact component={HomePage} />
<Route path="/research" component={ResearchPage} />

// HomePage/index.js

import Utility from './components/Utility';
import './styles.scss';
...
render(){
<div className="home-page">
<Utility />
</div>
}

// HomePage/styles.scss
.home-page {
...
}

// Utility/index.js

import './styles.scss';
...

render(){
return (
<div className="utility-comp">
...
</div>
}

// Utility/styles.scss
.utility-comp {
...
}

Load different style in a component based on routing

You cannot do that, as Angular requires the style declarations to be statically analyzable. This is done for the AOT compilation. All of your templates and styles are getting compiled to JavaScript when you run ng build --prod, and the styles are imported ahead of time. So, if you could reload styles using some conditionals, that code would no longer be statically analyzable (the screenSize variable can be known only during runtime, so which style should we import when building ahead of time?), thus resulting in the impossibility of AOT compilation.
(no, there is no way of compiling both styles and then importing them in runtime - that would mean we could understand what output will the function produce, which is virtually impossible - see halting problem)

But you can (and should) use ngClass to toggle between css classes depending on the screen size.

How to get different css files for different routes (express, node.js)

Is there any reason that you don't use template engine? Handlebars with layout option can solve this easily.

I found answer here https://stackoverflow.com/a/8790999/1822805

Why doesn't the CSS work on certain routes?

I think the problem is in your HTML

You adding your CSS file like this:

<link rel="stylesheet" href="styles.css">

And when your Url is something like /feed it would be ok, but on links like /something/here you would get your CSS searched as /something/styles.css. So you need to be specific and add / to your CSS declaration like this:

<link rel="stylesheet" href="/styles.css">

So your styles will always be searched from the root that is /



Related Topics



Leave a reply



Submit