CSS
Basics
Modern websites not only have to be performant, but they also have to look good. Also here, gg sticks close to web standards by supporting native CSS that can be added directly inside the TypeScript files next to your pages and components.
To keep the size of your page as small as possible, gg mangles class names and removes unused CSS out of the box. Otherwise, the CSS you write is not transformed in any kind of way. In particular, auto-prefixing is not supported at the moment.
Creating stylesheets
You can create a stylesheet using the gg.stylesheet method. It accepts a string as the single argument which will be parsed as CSS.
As mentioned, gg will mangle the names of all classes used in your CSS. So if you want to use a class to attach it to an HTML element, you need to use the getClass method defined on the stylesheet.
1const styles = gg.stylesheet(` 2 .red { 3 color: red; 4 } 5 .bold { 6 font-weight: bold; 7 } 8`); 9const markup = ( 10 <p class={[styles.getClass("red"), styles.getClass("bold")]}>Hello world</p> 11);
Note that gg will throw an error and won't compile the page if you try to get a class that does not exist in the stylesheet.
Global styles
If you want to add global styles to a page, you can pass a stylesheet containing the CSS to gg.page when creating a page.
1import { gg } from "../deps.ts"; 2 3const globalStyles = gg.stylesheet(` 4 body { 5 margin: 0; 6 } 7 ul > li { 8 line-height: 1.5; 9 } 10`); 11 12const PageComponent = gg.component(() => { 13 return ( 14 <html> 15 <body> 16 <ul> 17 <li>Hello</li> 18 <li>World</li> 19 </ul> 20 </body> 21 </html> 22 ); 23}); 24 25export const page = gg.page(PageComponent, { stylesheet: globalStyles });
Conditionally adding classes
When using client-side state it is a common use-case to add or remove some classes depending on some state. Before you read on here, make sure that you have made yourself familiar with state in gg.
If the classes of a particular element are depending on some state, you can create a selector for the state using the getClassMapSelector method provided by the stylesheet. You have to pass an object whose properties are the names of the classes you want to conditionally add to this method. The values are functions that will be called with the value of the state and should return a boolean, indicating if the class should be added or not.
1const styles = gg.stylesheet(` 2 .red { 3 color: red; 4 } 5 .bold { 6 font-weight: bold; 7 } 8`); 9 10const isBold = gg.state(false, { 11 getClasses: styles.getClassMapSelector({ 12 // This class will always be added 13 red: () => true, 14 // This class will only be added if the state is `true` 15 bold: (value) => value, 16 }), 17}); 18 19const markup = <p class={isBold.selectors.getClasses}>Hello world</p>;
At last, let's now learn about how to do basic state management on pages built with gg.
Next → State