DEV Community

Discussion on: What should production CSS look like? Share your layout-to-web workflow

Collapse
 
akashkava profile image
Akash Kava • Edited

I have created Web Atoms Core, which has CSS styling as JavaScript code.

class ListStyle extends AtomStyle {

    public get root(): IStyleDeclaration {
        return {
            color: Colors.gray,
            backgroundColor: Colors.white,
            subclasses: {
                " > li": {
                    color: Colors.blue,
                    subclasses: {
                        " > button": {
                            color: Colors.green
                        }
                    }
                },
            }
        };
    }
}

HTML

<script>
    import ListStyle from "~src/web/styles/ListStyle";
</script>
<ul
    default-style="{ ListStyle }"
    style-class="{ this.controlStyle.root }">
    <li>First Item</li>
    <li>Second Item</li>
    <li>
        Third Item
        <button>Delete</button>
    </li>
</ul>

In order to avoid naming conflicts in CSS, ListStyle class is instantiated once and root property style is given a css name that is unique. When we assign default-style it creates an instance of StyleSheet if it does not exist and attaches style to current component.

Best part is, IStyleDeclaration object is JavaScript object and it can contain any valid javascript and it refreshes when device size changes. You don't need media queries.

class ListStyle extends AtomStyle {

    public screen = (this.styleSheet as AtomTheme).app.screen;

    public get root(): IStyleDeclaration {
        return {
            width: this.screen.screenType === "mobile" ? "250px" : "900px"
        };
    }
}

Styles can be inherited and overridden easily as JavaScript objects. And you don't need to worry about how and where to put in assets. Also style will only be created for the components that are hosted in the page, making browser free of all unused CSS.