Box Model/CSS Positioning With Mondrian Style Art

Caston Boyd
13 min readMar 4, 2024

--

A digital rendition of Composition with Red Blue and Yellow Painting by Piet Mondrian

About this Article

When encountering something new, it’s natural to question its purpose and origins. Everything we interact with has been intentionally designed, reflecting a specific need or idea. This perspective is helpful when considering the digital transformation of real-world elements into web interfaces. By examining the CSS box model and positioning, we gain insights into the foundational techniques that make websites accessible and engaging for users. To illustrate the practical application of these concepts, we create a Mondrian abstract with CSS

What is the CSS Box Model?

The CSS Box Model is a box that wraps around every HTML element. It consists of four distinct parts: the content, padding, border, and margin.

You know that body tag we use to put all of the html content? That, at its core, is wrapped in a box. The p tag element that as well. All of these elements have the ability to

  1. Padding: The space between the content and the border.
  2. Border: A line that goes around the padding and content.
  3. Margin: The space outside the border.

Everything on a page, including the body, is a box with all the above parts.

You try playing around. Do the following steps to see the box model in action:

  1. Go to terminal
  2. Make a new directory called BoxModelPractice using mkdir
  3. cd into BoxModelPractice
  4. code . so you can open that folder in VS code
  5. create a new index.html
  6. Open index.html: Ensure index.html is open in your Visual Studio Code editor.
  7. Add Basic HTML Structure: If your index.html file is empty, start by adding the basic HTML5 document structure. You can quickly generate this by typing ! and pressing Tab if you have Emmet abbreviations enabled in VS Code. This will create the essential HTML boilerplate code.
  8. Write the div Element: Inside the <body> tag of your HTML document, add a div element with the text "Hello World" inside it. Your index.html and cssfiles should look something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Box Model Practice</title>
</head>
<body>
<div>Hello World</div>
</body>
</html>
div {
background-color: lightgray; /* Background color */
border: 2px solid black; /* Border */
padding: 20px; /* Padding around the text */
margin: 10px; /* Margin around the div */
}

Preview Your Work: To see your “Hello World” div in action, save your index.html file and open it in a web browser. You can usually do this by right-clicking the file in VS Code's explorer panel and selecting "Open with Live Server" if you have the Live Server extension installed, or simply by double-clicking the index.html file in your file explorer to open it with your default web browser.

Experiment and Learn: From here, you can experiment with different CSS properties related to the Box Model (like width, height, border-radius, etc.) to see how they affect the appearance of your div. This hands-on practice will deepen your understanding of the Box Model concept.

Content Box vs Border Box

When you pop open the dev tools and start inspecting elements, you’ll quickly notice something interesting when you tweak the width. As you dial up the width, it’s not just the content area that expands; the padding, borders, and margins stack on top, bulking up the total width more than you might have asked for.

This becomes a bit of a headache when you’re trying to fit elements into a precise layout. Let’s say you’ve got this design that’s just so, and then the additional padding and borders throw your measurements off kilter.

This is where the concept of box-sizing swoops in to save the day. By default, elements use what's called the content-box model. This means if you set an element to be 100px wide, that's the width of the content itself, not including padding or borders. So, if you add a 5px border and 10px padding, your element's total width isn't 100px anymore; it's 130px (100px content + 20px padding + 10px border).

But, switch that setting to border-box, and the game changes. Now, when you set an element to 100px width, that's the final size. Padding and borders are included within that width, not added on, making it way easier to plan your layout without needing a calculator by your side.

To really nail this concept down, let’s pit two divs against each other. One's playing by the content-box rules, and the other's rocking the border-box lifestyle. By comparing these side by side, you'll see how much smoother layout planning can be when you don't have to account for extra pixels added by padding and borders. This way, what you set is what you get, making your CSS much more predictable and your layouts crisp and clean.

So, that’s the box model in essence. It’s when every element on your page comes with its own set of invisible boundaries that dictate spacing and sizing. Grasping the difference between content-box and border-box is really important because it affects the total size of your elements and your entire layout. This understanding can simplify your CSS work, making your designs more predictable and easier to manage.

Document Flow

If we delve into the structure of a typical website layout, as seen above, you’ll notice it comprises various elements or “boxes.” If you take a moment to count, you’ll find there are five distinct “boxes”. This observation underscores the fact that elements do not exist in isolation on a screen; rather, they are placed next to each other, often separated by margins for clarity and aesthetic appeal. As a web developer, orchestrating these elements to lay out in a specific manner is part of your craft.

To put this into practice, let’s start with an experiment involving div elements, which are block-level elements by default. When you create two divs, you'll observe that they stack vertically on top of each other. This is because block-level elements naturally consume the full width available to them and start on a new line.

<div>First div</div>
<div>Second div</div>

Not every element, however, stacks on top of each other; some are arranged horizontally. This behavior is characteristic of what we call inline elements. Here’s an example to illustrate this concept:

<span>First inline element,</span> 
<span>Second inline element</span>

In this case, <span> elements are used, which are inherently inline. Unlike block-level elements like <div> that take up the full width available and start on a new line, inline elements only occupy as much width as their content requires and sit next to each other on the same line. This feature is particularly useful for styling text or grouping small chunks of content without breaking the flow of a document.

For a clearer demonstration, consider anchor tags (<a>), another common type of inline element:

<a href="#">First link</a> 
<a href="#">Second link</a>

Default Position for Websites

In HTML, the default positioning of elements, when no explicit CSS positioning is applied, is static. This means elements are laid out in the order they appear in the document flow. With static positioning, elements stack naturally on the page according to their placement in the HTML markup, and properties like top, right, bottom, left, and have no effect on them.

This default behavior ensures a straightforward, linear layout of elements, from block-level elements stacking vertically to inline elements lining up horizontally next to each other, based on their order in the code.

Our task is to harness and modify this default behavior to craft modern websites for our clients, companies, or personal projects. We achieve this by utilizing the position property in CSS. While the default static positioning doesn't permit us to move an element out of its normal document flow, there are several other positioning strategies that do, allowing for more flexibility and control in our designs. These include:

  • Relative: This allows us to move an element relative to its normal position, without altering the layout space it occupies.
  • Absolute: Positions an element absolutely to its nearest positioned ancestor, effectively removing it from the normal document flow.
  • Fixed: Fixes an element’s position relative to the viewport, making it stay in the same place even when the page is scrolled.
  • Sticky: A hybrid of relative and fixed positioning, where an element is treated as relative until it crosses a specified point, then it becomes fixed.

Relative Position

Relative Positioning is about tweaking an element’s position without affecting the space it occupies in the normal document flow. When you apply position: relative; to an element, you can then use top, right, bottom, and left properties to move it from its original location. However, it's important to note that the element still occupies the same space in the document as if it hadn't been moved, meaning other elements don't adjust to fill or make space for its new position.

Let’s illustrate an example of relative positioning by showing how to move one box relative to its original position, while keeping another box static for comparison. We’ll start with some simple HTML and CSS.

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p>
<div class="box-1">  </div>
<div class="box-2"> </div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p>

Static Position

.box-1 {
width: 200px;
height: 100px;
background-color: coral;
position: static;
top: 100px
}

When an element is positioned statically, it adheres to the natural document flow, meaning you cannot use positioning properties like top, right, bottom, or left to move it. This default behavior ensures the layout is predictable but offers limited flexibility for precise positioning adjustments.

Try it for yourself.

Relative Position

Let try changing the postion to relative to …

.box-1 {
width: 200px;
height: 100px;
background-color: coral;
position: relative;
top: 100px
}

Upon transitioning .box-1 to a relative position and nudging it 100px down, the space where .box-1 was initially positioned behaves as if the box is still there. This space does not collapse; it remains, preserving the layout's integrity as though .box-1 hadn't moved. This is a fundamental aspect of relative positioning: while the element moves visually, its original spot in the document flow is maintained as a placeholder, preventing other content from filling in. This behavior contrasts sharply with absolute positioning, where moving an element does cause the space it occupied to collapse, as the element is removed from the normal document flow.

Absolute Position

Now, if we change the position of our element to absolute, the behavior and impact on the layout are markedly different. With position: absolute;, the element is removed from the normal document flow. This means it no longer occupies space in the layout as it did before, which can lead to a noticeable shift in the surrounding content—often referred to as collapsing.

What happens with absolute positioning?

When an element is set to absolute positioning, it is positioned in relation to its nearest positioned ancestor—that is, the closest ancestor element with a position property set to anything other than static (such as relative, absolute, fixed, or sticky). This means the absolutely positioned element's placement (using the top, bottom, left, and right properties) is calculated based on the dimensions and position of that ancestor.

If there is no such positioned ancestor in the element’s hierarchy, the absolutely positioned element defaults to being placed relative to the initial containing block. The initial containing block is typically the viewport or the document body. This is a key concept because it determines how and where the absolutely positioned element will appear on the page.

For example, if you have a div element with position: absolute; and it's contained within another div that has position: relative;, the child div will be positioned absolutely in relation to the boundaries of its parent. However, if the parent div does not have a position set, or is set to static (the default), the child div will position itself absolutely in relation to the entire document or viewport.

Summary of box model and CSS positioning

Every HTML element is essentially a box with various components that dictate its appearance and layout on a webpage. Altering an element’s dimensions usually affects its content area, inadvertently increasing the overall size due to padding and borders. Switching the box-sizing attribute to border-box, however, changes this dynamic, allowing the element's total dimensions to encompass padding and borders, thus maintaining the intended size.

However, these elements don’t exist in isolation; they coexist and interact with other elements on the page. This interaction highlights the importance of understanding positioning, which plays a significant role in how elements are arranged and displayed. The concepts of static, relative, and absolute positioning are key to manipulating element placement. To deepen your grasp of these concepts, you’ll create a page that serves as a canvas for experimenting with these layout techniques, offering a practical way to explore and understand the intricacies of CSS positioning and the box model.

Explore CSS positioning with Modrian Art Page

A digital rendition of Composition with Red Blue and Yellow Painting by Piet Mondrian

In this section of the article, we’ll dedicate time to constructing the image mentioned earlier, leveraging our knowledge of CSS positioning and the box model. To begin, let’s first identify the various boxes depicted in this image.

There are approximately 8 to 9 boxes in total. Each box corresponds to an element displayed on the screen.

Before diving into the coding process, I’ve decided to assign class names to each box based on a screenshot of the webpage we’re recreating. This step will allow me to precisely adjust their positioning later, as I’ll have a clear reference to which element I’m modifying by matching the class names to the labels I’ve placed on my mockup.

I’m also considering the space each element occupies to estimate their width and height, as well as to anticipate their potential positions in terms of top, left, bottom, or right alignments.

Im doing all of this before I even considering HTML/CSS. I want to know the nature of my layout and discover what type of positionng and css tools i need to use in order to achieve my goal.

I’m undertaking all these steps even before diving into HTML/CSS. My aim is to thoroughly understand the layout’s nature and identify the types of positioning and CSS techniques required to achieve my desired outcome.

HTML for Modrian Art Page

Looking at the image again (which might require some time if you’re working through this by yourself), we notice a container with several boxes inside. This observation suggests the need for a parent class encompassing all other boxes as its children. This consideration is particularly useful when reflecting on relative and absolute positioning. While absolute positioning removes an element from the normal document flow, positioning a child element in relation to a parent (ancestor) element can effectively manage its placement. Refer to the image below for clarity.

Image from W3School

Remember also to properly configure your container at the outset, setting its positioning to relative. This step is crucial as it enables the container to act as an ancestor for any contained element that is positioned absolutely.

<div class="container"> 

</div>
*{
margin: 0;
padding:0;
box-sizing: border-box;
}
.container {
min-height: 95vh;
background-color: white;
margin: 20px;
border: black solid 10px;
position: relative;
}

Let’s start by situating each element inside a container, for example, box_one_white, ensuring it's placed accurately according to the class name selectors we previously defined.

<div class="container"> 
<div class="box_one_white"></div>
</div>

Let’s apply position: absolute to position the elements based on our earlier estimations. Feel free to experiment with this to gain more practice and familiarity.

*{
margin: 0;
padding:0;
box-sizing: border-box;
}
.container {
min-height: 95vh;
background-color: white;
margin: 20px;
border: black solid 10px;
position: relative;
}
.box_one_white {
position: absolute;
background-color: #D3CEC5;
height: 40%;
width: 20%;
border: 10px solid black;
}

Continue applying the same process we used for box_one_whiteto the rest of the elements on your own. Gradually work through each one, implementing the positioning and alignment techniques we’ve discussed, until your page closely resembles the layout shown in the provided screenshot.

Center the name box in the document

To center an element perfectly within its parent, you can apply a combination of CSS properties that leverage absolute positioning and the transform property. Here’s a concise guide using the .name_box class as an example:

  1. Positioning: First, set the element’s position to absolute. This removes it from the normal document flow and allows it to be positioned relative to its nearest positioned ancestor.
  2. Centering Coordinates: Next, align the element to the exact center by setting both top and left properties to 50%. This moves the top left corner of the element to the center of the parent.
  3. Offset Adjustment: However, this approach alone will place the element’s top-left corner at the center, not the element itself. To truly center the element, apply a transform with translate(-50%, -50%). This adjusts the element back by half of its own width and height, aligning its center with the parent's center.
  4. Styling: Add any additional styles you need, such as border, padding, background-color, font-family, and font-size to enhance the visual appearance of the centered element.

Conclusion

That concludes our practice session on box modeling and positioning with CSS. Hopefully, this has given you a solid understanding of how web pages are structured and the ways in which elements within them can be manipulated and positioned to create effective and visually appealing layouts.

--

--