Development

Separation of Style and Content — Why MUI Sucks

In the rapidly evolving world of web development, the ongoing debate over best practices for designing and structuring applications is more relevant than ever. One focal point of this debate is the practice of integrating styling directly within JavaScript components, an approach popularized by libraries such as Material-UI (MUI). MUI, along with similar frameworks, provides developers with a comprehensive suite of React components that conform to the Material Design guidelines, offering a seemingly quick path to prototyping and interface building. This convenience, however, may come at a significant cost, impacting not just code verbosity but also challenging the core web development principles of maintainability, scalability, and the crucial separation of content and presentation.

By blending the concerns of styling and logic within the same code constructs, such practices raise substantial questions about the long-term implications for web projects. While they promise speed and visual consistency out of the box, they necessitate a closer examination of how these benefits weigh against the potential for increased complexity and the dilution of foundational web standards.

LaTeX: A Standalone Beacon of Separation

LaTeX, a high-quality typesetting system, is a powerful exemplar of the importance of separating content from design. Originating from TeX, a typesetting system developed by Donald Knuth in the late 1970s, LaTeX was later extended by Leslie Lamport to make TeX more accessible and to support a higher level of abstraction. This evolution allows authors to focus solely on the content, freeing them from the intricacies of formatting. As a result, their work is presented consistently and professionally, with LaTeX handling the complex layout tasks invisibly. This separation ensures that the essence of the document remains distinct and untangled from its visual presentation, embodying the principle that good design should facilitate content, not obstruct it.

LaTeX is particularly revered in academic and scientific communities for its precision and efficiency in handling documents that contain complex mathematical expressions, bibliographies, and cross-references. It has become the de facto standard for many scientific publications, thesis documents, and conference papers. Its ability to produce publication-quality texts makes it an indispensable tool for researchers and academics worldwide, further showcasing the timeless value of distinguishing between the substance of one’s work and the manner in which it is visually rendered.

Office Templates: A Parallel in Document Writing

In the corporate world, the principle of separating content from its presentation finds a practical application through the use of templates in office suites such as Microsoft Office, Google Docs, and LibreOffice. These software solutions offer a variety of templates that empower users to concentrate on delivering their core message, while relying on pre-designed styles to ensure that documents adhere to a consistent and professional appearance. This functionality not only streamlines document creation but also elevates the quality of output by abstracting the complexities of design.

Despite the availability of these powerful tools, the effective use of templates remains underutilized in many business environments, leading to inefficiencies and a lack of standardization across documents produced within the same organization. The disparity between the potential for streamlined, professional document creation and the reality of inconsistent application underscores a broader challenge in corporate document management. But that’s a whole different story. Nevertheless, the concept of using templates as a means to separate content from presentation underscores a fundamental principle shared across fields ranging from digital publishing to web development: the true value of content is most fully realized when it is presented clearly and without unnecessary complication by design elements.

The Semantic Web: A Foundation Forgotten

The web has long embraced the principle of separation of concerns — a guideline advising that different aspects of application development, such as content, presentation, and behavior, be managed independently. This principle is not arbitrary; it is the culmination of decades of experience and evolution. From the early days of inline styles and table-based layouts to the adoption of CSS for styling, the web’s history is a testament to the ongoing effort to create more maintainable, accessible, and flexible ways to build the web.

The foundation of the web is built on HTML – a language designed to structure content semantically. This means that tags such as <button>, <header>, <article> or <footer> are not just stylistic choices but convey the meaning and role of the content they encapsulate. This semantic approach is vital for accessibility, search engine optimization, and maintainability.

CSS was introduced to separate the concerns of styling from content structure, allowing HTML to focus on content and semantics, and CSS to manage presentation. This separation is a cornerstone of web development best practices, ensuring that content is accessible and usable across different devices and by users with diverse needs.

The Pitfalls of Mixing Style and Content

Breaking Consistency

One of the strongest arguments against embedding style directly within components, as is common in MUI, is the risk to consistency. Components scattered across a project may be styled differently due to the variability of inline styling or prop-based design adjustments. This piecemeal approach can lead to a fragmented user interface, where similar elements offer differing user experiences.

High Maintenance Costs

While mixing design and content can expedite prototyping, it introduces significant long-term maintenance challenges. Styles tightly coupled with logic are harder to update, especially when design changes require navigating through complex component structures. This can lead to a bloated codebase, where updates are slow and error-prone.

The Designer-Developer Handoff

The collaboration between designers and developers is crucial to the success of any project. By mixing styles with component logic, we blur the lines of responsibility, potentially leading to confusion and inefficiencies. Designers are experts in creating user experiences, while developers excel at implementing functionality. The separation of concerns respects these specializations, ensuring that both can work effectively towards a common goal without stepping on each other’s toes.

The Problem with MUI’s Approach

MUI, while offering a rich set of components for rapid development, often blurs the lines between content structure and presentation. This is evident in the verbosity and explicit styling present within component definitions. Consider the following MUI example:

import React from 'react'
import Grid from '@mui/material/Grid'
import Typography from '@mui/material/Typography'
import Button from '@mui/material/Button'
import {Link} from 'react-router-dom'

function MyComponent() {
  return (
    <Grid container spacing={2}>
      <Grid item xs={12} sm={6}>
        <Typography variant="h1" gutterBottom>
          Welcome to My App
        </Typography>
        <Typography variant="body1">
          Get started by exploring our features.
        </Typography>
        <Button variant="contained" color="primary" component={Link} to="/start">
          Get Started
        </Button>
      </Grid>
    </Grid>
  )
}

In this snippet, the presentation details are deeply intertwined with the component’s structure. It is full of complexity, such as spacing={2}, xs={12}, sm={6} introduce arbitrary numbers without any context. The only reason for Grid and Typography elements is influencing the appearance, they have no semantics. This kind of pseudo-components should never be used. The properties spacing, xs, sm, variant, gutterBottom, color, and contained dictate the appearance directly within the JSX. This again violates the principle of separating style and content, leading to a scenario where changing the design necessitates modifications to the component code. So the react MUI library is the worst front-end library I have ever seen.

Advocating for a More Semantic Approach

Contrast the MUI example with an approach that adheres to the separation of concerns principle. Instead of mixing appearance and content, the full example above can be replaced by a simple standard HTML button within some semantic context, such as a navigation. First you either use an existing library, or you simply define your components, this is a sample for a clean and properly designed component:

import React from 'react'
import {Link} from 'react-router-dom' 

function ButtonLink({to, children}) {
  return <Link className='button' to={to}>{children}</Link>
}

Then you just use your component. Please note that outside of the definition of basic components, you must not use className or any other attribute that defines semantics or styling. Define base components for this purpose, then all remaining attributes, such as to, have a fully functional meaning. The resulting code is very clean and simple, so it is easy to read and maintain:

import React from 'react'
import {ButtonLink} from '@my/components'

function AppHeader() {
  return (
    <header>
      <p>Welcome to My App</p>
      <p>Get started by exploring our features.</p>
      <ButtonLink to='/start'>Get Started</ButtonLink>
    </header>
  )
}

Here you immediately see the content, so you can focus on the relevant parts.

For the look and feel, just apply some styling, which needs to be written only once in a central CSS style file, something like e.g.:

header {
  display: flex;
  justify-content: space-between;
}
button, a.button {
  color: white;
  background-color: blue;
  padding: 1ex;
  border: .1ex solid black;
  border-radius: .5ex;
  cursor: pointer;
}

In this simple example, CSS styles the layout inside of your <header>-tag, which replaces all that <Grid> and <Typography> nonsense, moreover the <button> tag and links in button style are both styled identically using CSS, ensuring that all button like elements across the application maintain a consistent appearance without requiring explicit style definitions in the code. This not only reduces redundancy but also aligns with the semantic nature of HTML, where the tag itself carries meaning.

Furthermore, thanks to the separation of styling and content, a designer can write the CSS and give you basic HTML layout rules, then the developers can focus on the content, instead of having to pay attention to the look and feel.

Please refer to our post Write a Common CSS Style Library for more details on how we suggest to structure your front-end libraries by separating styles from components, templates and content.

The Real Cost of Convenience

While MUI and similar libraries offer rapid development capabilities, they do so at the expense of long-term maintainability, scalability, and adherence to web standards. The explicit declaration of styles and layouts within JSX components leads to a verbose codebase that is harder to maintain and less accessible.

The additional typing and complexity introduced by such frameworks can obscure the semantic nature of the web, making it more challenging to achieve a clean, maintainable, and accessible codebase. This is contrary to all best practices and conflicts with the evolution of web standards, which have consistently moved towards a clear separation of content and presentation.

Embracing Standards for a Sustainable Web

The allure of quick development cycles and visually appealing components cannot be underestimated. However, as stewards of the web, developers must consider the long-term implications of their architectural choices. By embracing HTML’s semantic nature and adhering to the separation of concerns principle, we can build applications that are not only maintainable and scalable but also accessible to all users.

As the web continues to evolve, let’s not forget the lessons learned from its history. Emphasizing semantics, maintaining the separation of content and presentation, and adopting standards-based approaches are crucial for a sustainable, accessible, and efficient web.

Defending Separation of Style and Content

Critics of separating style from content may argue that modern web development practices, like CSS-in-JS, enhance component re-usability, enable dynamic styling, and streamline the development process by colocating styling with component logic. However, adhering to the separation of style and content principle offers significant long-term benefits. It enhances maintainability by allowing changes in design without altering the underlying HTML structure or JavaScript logic. This separation fosters accessibility and scalability, ensuring that websites and applications can grow and adapt over time without becoming entangled in a web of tightly coupled code. Additionally, it aligns with web standards and best practices, promoting a clear organizational structure that benefits developers and designers alike. By maintaining this separation, developers can leverage the strengths of CSS for styling, HTML for structure, and JavaScript for behavior, leading to a more robust, flexible, and accessible web.

For those inclined to integrate styling within React, an advisable approach is packaging styles into a dedicated Style and Component Library. This library should encapsulate the styling based on the Corporate Identity, allowing the actual code to utilize components devoid of additional styling. This methodology garners benefits from both paradigms. However, it’s crucial to note that this often falls short in meeting accessibility standards and restricts the styling’s applicability outside the chosen framework (e.g., React or Angular). In contrast, segregating styling from HTML via CSS and subsequently crafting components ensures technological independence, enabling the same styling to be utilized in diverse contexts like a PHP-based WordPress theme, showcasing its versatility across various platforms.

Development

Write a Common CSS Style Library

As a company that creates various products and services, mostly web applications and web based services, it is very important for Pacta Plc to have clear company identity with common look and feel in all our products and public appearances. Therefore our first step was to get official company corporate brand identity guidelines, a so called corporate identity CI. After having received our guidelines, the same designer was hired for creating a landing page. The result is what you now can see as our Pacta.Swiss corporate page. What the designer delivered, was only a sketch of the final result, which had to be implemented in HTML and CSS. Pacta styling follows best practices:

  • Pure CSS3 + HTML5.
  • No JavaScript for the basic layout. JavaScript is used in the basic design only to obfuscate the email address.
  • Clear separation of styling and structure.
  • All dimensions are relative to context (%), font (rem, em, ex) or browser size (vh, vw).
  • No absolute dimensions (no px allowed).
  • Initial font size is not defined, so the user’s configuration is respected.
  • No inline styling in HTML elements (no style=).
  • Styles are attached to HTML by element name or class.

Basic technical decisions:

  • Build environment is npm.
  • CSS is generated using Stylus processor.
  • Supported development environment is Linux only.

Initial Project Setup

We created an project pacta/style, that contains a file package.json and a folder for fonts, images, scripts and stylus.

package.json

The file package.json just holds the basics for CSS from Stylus:

  • A script npm install to install Stylus.
  • A script npm run-script build to build CSS.
  • A script npm start to rebuild when a file changed . inotifywait is a Linux tool to monitor file system changes.
{
  "name": "pacta-style",
  "version": "1.0.0",
  "dependencies": {
    "stylus": "^0.54.7"
  },
  "scripts": {
    "build-css": "stylus -c stylus/ --out css",
    "run-css": "while inotifywait -qq -e modify -r style/stylus; do npm run build-css; done",
    "build": "npm run build-css",
    "start": "npm run build-css && npm run run-css"
  }
}

All Stylus sources are in directory stylus and CSS targets are generated to directory css. This pacta/style project is included as git submodule in all other projects.

root.styl

To get a consistent look and to keep it easy to change basic settings, there are CSS variable definitions e.g. for the color palette, for basic spacing,  for the border style or for the shadow definition.

:root
    --blue100 #002b5e
    --blue90 #013466
    --blue80 #034072
    --blue70 #034b7c
    --blue60 #045a89
    …
    --border 0.1em solid var(--blue100)
    --shadow 0 0.25rem 0.25rem 0 rgba(0, 0, 0, 0.14),
        0 0.5rem 0.1rem -0.25rem rgba(0, 0, 0, 0.12),
        0 0.1rem 0.75rem 0 rgba(0, 0, 0, 0.2)
    …

grid.styl

The styles define all objects in all resolutions based on element name or class, such as grids or cards:

.grid2, .grid3, .grid4
  --grid-size 1fr
  display grid
  grid-template-columns: repeat(var(--grid-columns), var(--grid-size))
  grid-auto-rows: min-content 
.grid2
  --grid-columns 2
.grid3
  --grid-columns 3
.grid4
  --grid-columns 4
@media all and (max-width: 120rem)
    .grid4
        --grid-columns 2
@media all and (max-width: 80rem)
    .grid2
        --grid-columns 1
@media all and (max-width: 60rem)
    -grid4, .grid4
        --grid-columns 1

card.styl

.card
    display: grid
    grid-template-columns: auto 1fr
    border: var(--border)
    shadow: var(--shadow)
    width: calc(100% - 2em)
    .icon
        background-color: var(--blue100)
        width: 3rem
        height: 3rem
        border-radius: 50%
        svg, object, img
            width: calc( 100% - .2em )
            height: calc( 100% - .2em )
    > .heading
        background-color: var(--heading-bg)
        &, h1, h2, h3, h4, h5, h6
            color: var(--heading-color)
    .content
        display: flex
        flex-flow: column nowrap
        margin: .5em
        width: calc(100% - 1em)

The Landing Page

Our company landing page is Pacta.Swiss, where the company and its products are introduced. This is implemented as a static HTML page using the generated CSS. In fact, two pages, in English and German. The matching language is set from the browser through HTTP content negotiation by an Nginx server. This page’s implementation looks like:

  <body>
    <header>
      <div class="logo">
        <img src="style/images/logo.svg" alt="" /><span>Pacta AG</span>
      </div>
      <div>
        <nav class="social">
          <a>…</a>
          <a>…</a>
        </nav>
      </div>
    </header>
    <main>
      …
      <div class="container">
        <h2>…<span class="subtitle">…</span></h2>
        <div class="grid6">
          <div class="card">
            <div class="icon"><svg>…</svg></div>
            <div class="content">
              <h3>…<span class="subtitle">…</span></h3>
              <p>…</p>
              <div class="bottom"><a>…</a></div>
            </div>
          </div>
          <div class="card" disabled>
            <div class="icon"><svg>…</svg></div>
            <div class="content">
              <h3>…<span class="subtitle">…</span></h3>
              <p>…</p>
              <div class="bottom"><a>…</a></div>
            </div>
          </div>
          …
          </div>
        </div>
      </div>
      <div class="to-inverse" />
      <div class="inverse">
        <div class="container">
          <h2>…<span class="subtitle">…</span></h2>
          …
        </div> 
        …
      </div>
    </main>
    <footer>…</footer>
  </body>

React Components

Our software consists of Progressive Web Applications written in ReactJS. So we need a react component library. For this, we simply created another git project pacta/components that only contains a large amount of JavaScript React Component files and is included as git submodule into all development projects. Based on the work above, it is very easy to implement React Components, just define the parameters and return the necessary HTML structure.

Grid.js

This is the full definition of our grid layout, where you can specify size as the maximum number of grid columns. The actually shown number of grid columns depends on the browser width, as defined in the CSS you see in the snipped above:

import React from 'react';
import PropTypes from 'prop-types';

export default class Grid extends React.PureComponent {
  static propTypes = {
    children: PropTypes.oneOfType([
      PropTypes.array,
      PropTypes.object,
      PropTypes.string
    ]),
    size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    type: PropTypes.string,
  };
  render = () => (
    <div
      className={
        'grid' +
        this.props.size +
        (this.props.type ? ' ' + this.props.type : '')
      }
    >
      {this.props.children}
    </div>
  );
}

Card.js

A card may have an icon and a heading:

import React from 'react';
import PropTypes from 'prop-types';
import MdiIcon from '@mdi/react';

export default class Card extends React.PureComponent {
  static propTypes = {
    children: PropTypes.oneOfType([
      PropTypes.array,
      PropTypes.object,
      PropTypes.string
    ]),
    type: PropTypes.string,
    icon: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
    heading: PropTypes.oneOfType([PropTypes.string, PropTypes.object])
  };
  heading = () =>
    typeof this.props.heading === 'string' ? (
      <h2>{this.props.heading}</h2>
    ) : (
      this.props.heading
    );
  render = () => (
    <div
      className={
        'card ' + (this.props.type || '') + (this.props.icon ? '' : ' noicon')
      }
    >
      {this.props.icon ? (
        <div
          className={'icon' + (this.props.type ? ' ' + this.props.type : '')}
        >
          {typeof this.props.icon === 'string' ? (
            <MdiIcon path={this.props.icon} />
          ) : (
            this.props.icon
          )}
        </div>
      ) : this.props.heading ? (
        <div className="heading">{this.heading()}</div>
      ) : (
        <></>
      )}
      {(this.props.children || (this.props.heading && this.props.icon)) && (
        <div className="content">
          {this.props.heading && this.props.icon ? this.heading() : <></>}
          {this.props.children}
        </div>
      )}
    </div>
  );
}

Usage Example

As a usage example for the above samples, here is a snippet from the landing page on Pacta.Cash:

class LandingPage extends React.Component {
  …
  render = () => (
    <>
      <StepsToCoin current={this.props.current} />
      <Container>
        <h2>
          {this.props.t("landingpage.titlewhy")}
          <span className='subtitle'>
            {this.props.t("landingpage.subtitlewhy")}
          </span>
        </h2>
        <Grid size='4'>
          <Card icon={this.FAQ}>
            {this.props.t("landingpage.wheretouse")}
            <p className='bottom'>
              <button disabled>{this.props.t("landingpage.more")}</button>
            </p>
          </Card>
          <Card icon={this.FAQ}>
            {this.props.t("landingpage.investment")}
            <p>
              <img src={ChartImage} alt='Ethereum chart of one year' />
            </p>
            <p className='bottom'>
              <button disabled>{this.props.t("landingpage.more")}</button>
            </p>
          </Card>
          <Card icon={this.FAQ}>
            {this.props.t("landingpage.privacy")}
            <p className='bottom'>
              <button disabled>{this.props.t("landingpage.more")}</button>
            </p>
          </Card>
          <Card icon={this.FAQ}>
            {this.props.t("landingpage.independence")}
            <p className='bottom'>
              <button disabled>{this.props.t("landingpage.more")}</button>
            </p>
          </Card>
        </Grid>
      </Container> 
      …
  }
}

WordPress Template

Last but not least, our blog is written in WordPress, so Pacta also needs a WordPress template in the same style. Here we do the same, as with the React Component library, only that the template is now written in PHP instead of NodeJS.

wordpress.styl

There is only a very small additional Style file for WordPress specific definitions. All other definitions are comonnly shared:

html body #wpadminbar
    height: 46px
    width: 100%

.wp-type
    margin: 0 1em
    display: flex
    flex-flow: row nowrap
    justify-content: space-between

index.php

A WordPress template requires at least an index.php file, so let’s show this as an example:

<?php get_header() ?>

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

<?php if (has_post_thumbnail()) : ?>
<div class="cropped-image">
    <?php the_post_thumbnail('full') ?>
</div>
<?php endif ?>

<div class="wp-type">
    <div>
        <?php the_category(' ', ' → ') ?>
    </div>
    <div>
        <?php the_tags('', ' ', '') ?>
    </div>
</div>
</div>
<div class="container">
    <article>
        <h1><?php the_title() ?></h1>
        <?php the_content() ?>
    </article>
</div>

<?php endwhile; ?>
<?php endif; ?>
<?php get_footer() ?>

Pacta PagesServices and Pages by Pacta AG

Pacta.Cash

This is the easiest crypto wallet on the market. Manage your Ethers and Bitcoins securely without having to understand the technical details. You own the keys, all data is stored on your device. Trade without registration.

Pacta.Swiss

Company representation page of the Swiss Pacta Corporation Pacta Plc. This page is provided by Pacta Plc (in German: Pacta AG).