Video Tutorial Create a container


I propose today to talk about an element that we find very often in our web pages, the container. This element allows to include several sub-elements in order to center them on the page (this makes it possible to prevent the content spreading over the entire width of the screen, which can affect readability in the context of large screens. ).

We can then wonder what solution to choose to create this type of element?

Automatic margins

The first strategy is to give our element a fixed width and then use the automatic margins in order to center and our content.

.container {
    width: 1000px;
    margin-left: auto;
    margin-right: auto;
}

It is possible to replace our width with a max-width which will allow us to properly manage the case of smaller screens.

.container {
    width: calc (100% - 40px);
    max-width: 1000px;
    margin-left: auto;
    margin-right: auto;
}

We can improve the flexibility of our script by adding CSS variables.

: root {
    --container-padding: 20px;
    --container-width: calc (100% - var (- container-padding) * 2);
    --container-max-width: 1000px;
}

.container {
    width: var (- container-width);
    max-width: var (- container-max-width);
    margin-left: auto;
    margin-right: auto;
}

Variables allow you to gain flexibility and you can for example change the value of the container according to the resolutions.

Padding & calc

The main problem with the previous approach is that using margin will prevent us from applying a background color to our element and we will then have to use several elements in our HTML.

It is however possible to remedy this problem by using another alignment technique based on the inner margins rather than the outer margins:

: root {
    --container-padding: 20px;
    --container-width: calc (100% - var (- container-padding) * 2);
}
.container {
    box-sizing: border-box;
    width: 100%;
    padding-left: calc (50% - var (- container-width) / 2);
    padding-right: calc (50% - var (- container-width) / 2);
}

@media only screen and (min-width: 1040px) {
    : root {
        --container-width: 1000px;
    }
}

Unfortunately, it is not possible to energize this media-query using CSS variables, because they are not supported at this level. We suddenly lose a little flexibility compared to the previous method because it will be necessary to do the calculation manually to define the different media-queries. On the other hand, this allows you to simplify the HTML code and limit unnecessary divs: