An example of how to refactor CSS using the Composition layer of CUBE methodology

Existing code

In this example, we have a group of buttons that have to be evenly spaced horizontally and vertically. The buttons should also wrap onto the next line when there is no more space horizontally.

The current implementation uses Bootstrap and the HTML looks like this

<div class="d-flex flex-row">
    <button class="btn btn-primary mr-3 mb-2">
        Button 1
    </button>

    <button class="btn btn-primary mr-3 mb-2">
        Button 2
    </button>

    <button class="btn btn-primary mr-3 mb-2">
        Button 3
    </button>

    <button class="btn btn-primary mr-3 mb-2">
        Button 4
    </button>

    <button class="btn btn-primary mr-3 mb-2">
        Button 5
    </button>
</div>

The above snippet does not follow the Composition layer of CUBE as each button has to know how to space itself.

Ideally, the outer div would orchestrate the positioning of each button. The button would then only be responsible for its styling in isolation.

Refactor

The above snippet is trying to achieve an evenly spaced layout of buttons, but currently, each button is responsible for the space between items. The spacing should be a responsibility of the wrapping div

For modern browsers in this instance is a simple fix. We add the gap-3 class to the wrapping div and remove mr-3 & mb-2 from each button.

<div class="d-flex flex-row gap-3">
    <button class="btn btn-primary">
        Button 1
    </button>

    <button class="btn btn-primary">
        Button 2
    </button>

    <button class="btn btn-primary">
        Button 3
    </button>

    <button class="btn btn-primary">
        Button 4
    </button>

    <button class="btn btn-primary">
        Button 5
    </button>
</div>

As much as these exact classes might not work in your circumstance, the principle remains the same.

Roughly speaking an individual element should not be bothered about other elements positioning - margin is usually a telltale sign.

Where you find elements worrying about the position of others, try looking at the instance from the level above, e.g. the container div, and take a Composition based approach when refactoring.