Open CheatSheet Back To List Next Tutorial

Spacing: Box Model and Dimensions (Video Tutorial)

Spacing: Box Model and Dimensions

Intro to Spacing: Length and Box Model

Build a Blog Site: This is the fifth part of the Build a Blog Site tutorial series.
The focus of this tutorial is on Spacing. It includes understanding the most commonly used measurement units (pixels, em, rem, percents, vw and vh). And understanding the Box Model which includes padding, margin and borders. We will apply these to our Blog Site example.

Simulate Bootstrap: In this tutorial series we are mimicking Bootstrap classes, using the same Bootstrap class names, and applying the same or similar style but with less complex style rules.

Finished Code: The code is available on GitHub: github.com/LearnByCheating/learn-html-blog-site-example. There is a separate version with the finished code for each tutorial.

Live Server: If you are using VS Code as your text editor and have the Live Server extension installed, you can launch a local web server from the Editor.
  • Close any prior Live Server sessions by right-clicking in the editor, then select Stop Live Server.
  • If you are using the code from the GitHub link above, go to the .vscode/settings.json file and change the liveServer.settings.root value to the appropriate version: "liveServer.settings.root": "/v5-spacing" 
  • Right click in the html page and select "Open with Live Server". 

Written and Video tutorial: There are both a video and written version of each tutorial. For the HTML-CSS tutorial series the video and written versions have a different focus. The video tutorials are focused on the blog site project. The written tutorial is focused on the all the subtopics within the CheatSheet major topic.

CheatSheet: Part of the objective of this tutorial series is to become familiar with the CheatSheet so you can use it for quick reference going forward. As such, it is recommended that you review the CheatSheet category that aligns with this tutorial.



Length and Percentages

[0:00 Video timestamp]

First let's cover length and percentages (see CheatSheet: Length category: Length and percentages).

Length is a CSS data type that represents a distance value. 
Common CSS properties that use length include width, height, margin, padding, border-width, font-size, text-shadow.

Length Units

Length can be measured in absolute or relative units.

Absolute Length Units
[0:25 Video timestamp]

The most commonly used absolute unit in web development is pixels, expressed as px.
A pixel is 1/96th of an inch or approximately 1/38th of a centimeter.
The default font-size for the major web browsers is 16 pixels or 16px. 
You could set font-size on your web page to 14px from your stylesheet like this: 
body { font-size: 14px; } 

Relative Length Units
[3:41 Video timestamp]

You can set length using relative units em or rem. 

rem: Sets the length relative to the font-size of the root element, which by default is 16px.
  • 1rem is 16px. 
  • .5rem is 8px.
  • 2rem is 32px.

Example:

<p style="font-size: 2rem>Some text.</p>
2rem font size would be 16 x 2 = 32px.

To change the root font-size you need to set it on the html tag:
html { font-size: 14px; }

Then:
<p style="font-size: 2rem>Some text.</p>
2rem font size would be 14 x 2 = 28px.

em: Sets the length relative to the font size of the element. So if the font-size of an ancestor element was changed, em would be in relation to the new font size. 

Example:
<div style="font-size: 20px">
  <p>Some text.</p> <p style="font-size: 2em>Some more text.</p>
</div>
The font size of the first p element is 20px which it inherits from its ancestor elements. In this case from its parent div.
The font size of the second paragraph was set to 2em which translates to 20 x 2 = 40px

Of the two, em vs rem, rem has the advantage of consistency. It won't be affected by changes in font-size of any ancestor elements. For this reason, Bootstrap generally rem to set length values.

Percentages
[2:32 Video timestamp]

Length can also be set as a percent of the parent element. Percent values are often used when you want elements to shrink and grow proportional to the browser window size. 
For example, the below image element width is set to 25%. Body is the parent element so it will take up 25% of the screen width.
<body>
  <img src="images/mypic.png" style="width: 25%">
</body>

Viewport Units
The viewport is the area of a web page that's visible to the user.
Viewport units set the width or height as a percent of the device's viewport.
It is not affected by the width or height of the parent element.

vw: Sets the element width as a percent of the viewport width. 
vh: Sets the element height as a percent of the viewport height. 

In the below example, the image takes up 25% of the viewport's width and 50% of the height. The width or height of the parent element does not affect the the vw or vh result.
<div style="width: 500px">
  <img src="images/placeholder-x.png" style="width: 25vw; height: 50vh">
</div>



Box Model

(see CheatSheet: Box Model category)
[5:13 Video timestamp]

All elements have a box around them that includes:
  • Content: the content of the element such as text, or an image. 
    • The content area has properties for width and height.
  • Padding: the space surrounding the content is called padding.
  • Border: The edges of the element are its border. Some elements,  buttons and form input boxes, have a visible border by default.
  • Margin: The space surrounding an element is called margin. Margin separates the element from surrounding elements. 


Display property

All elements have a default display property that specifies its display behavior (see CheatSheet: Other Properties category: Display).

Values include:
  • None: element not displayed.
    • Some elements are not displayed at all by default including head, meta, link, title. 
    • display: none; You can hide any element by changing its display property value to none.

  • Block: block elements take up the full width available (of the parent element) and have a line break before and after them.
    • Common block elements include: div, body, h1-h6, p, li, form, hr, nav, main, footer, section.
    • You can set width, height, padding, margin, and border properties for block elements.
    • display: block; You can change the display property to block to make an element (e.g., button, img) take up the whole line.

  • Inline: inline elements only take up as much room as needed and do not add line breaks before and after the element.
    • Common inline elements include: span, b, strong, i, em, u, a, small, img, label.
    • You can set border, left and right padding and margin for inline elements. 
    • You cannot set width, height, or top and bottom padding and margin.
    • For images, you can set the height property. That will change the line-height property.
    • display: inline; Sets display property to inline.

  • Inline-block elements: Combines aspects of inline and block elements. 
    • Common inline-block elements include: button, input, textarea, select.
    • By default, the width of an inline-block element is just the room needed.
    • You can set width, height, padding, margin, and border properties like for block elements.
    • display: inline-block; Sets display property to inline-block.



Blog Site: spacing classes and style rules

See the Blog Site changes

To see what the change results are going to be, open the Blog-Site-V5 in VS Code.
  • Make sure you changed the .vscode/settings root to "/blog-site-v5"
  • Open the index.html page, right click in the Editor and select Open with Live Server.
  • In the browser view the starting version at http://localhost:5500/index-start.html
  • Then view the changes in the index.html file at http://localhost:5500

The Bootstrap CDN
To see the site styled using the Bootstrap CDN:
  • Comment out the local style.css stylesheet. 
  • Uncomment the Bootstrap CSS CDN. 
  • Refresh the web page. It should look the same with Bootstrap. 
  • Put it back to using your local stylesheet. Comment out the Bootstrap CDN and uncomment the local styles.css stylesheet.


Spacing classes

In the index.html file, add Bootstrap classes to the elements that you want to add spacing to.
The Bootstrap spacing classes are listed at: getbootstrap.com/docs > click Utilities: spacing.

Below is the index.html code with the spacing classes in bold. 
index.html
<head>
  ...
  <!-- <link rel="BOOTSTRAP CSS CDN"> -->
<link href="stylesheets/styles.css" rel="stylesheet"> </head> <body>
  <nav class="text-white bg-dark mb-4"> 
    <div class="container">
      Navigation Bar Here
    </div>
  </nav>
  <main class="container">
    <article class="text-white bg-dark p-4 p-md-5 mb-4 rounded">
      <div class="col-md-8 px-0 width-67">
        <h1 class="mt-0">Highlighted Article title 1</h1>
        <p class="my-3">Summary and link. Lorem ipsum...</p>       
      </div>
    </article>
    <div class="row g-5 grid-67-33">
      <div class="col-md-8">
        <article class="mb-3 border-bottom">
          <h3>Highlighted Article title 2</h3>
          <p class="text-muted">Author and date</p>
          <p>Summary and link.</p> 
        </article>
        <article class="mb-3 border-bottom">
          <h3>Highlighted Article title 3</h3>
          <p class="text-muted">Author and date</p>
          <p>Summary and link.</p> 
        </article>
        <article class="mb-3 border-bottom">
          <h3>Article title N</h3>
          <p class="text-muted">Author and date</p>
          <p>Summary and link.</p> 
        </article>
      </div>
      <div class="col-md-4">
        <aside class="bg-light p-4 mb-3 border rounded">
          <h4 class="mt-0">About</h4>
          <p>About you, your business, and/or your blog content focus. </p>
          <p>Lorem ipsum...</p>
          <address>email: me@example.com</address>
        </aside>
      </div>
    </div>
  </main>
  <footer class="bg-light mt-3 py-4 border-top">
    <div class="container">
      Footer Here
    </div>
  </footer>
  <script src="BOOTSTRAP JAVASCRIPT CDN"></script>
</body>

Below is the article-template.html code with the spacing classes in bold. 
articles/article-template.html
<body>
  <nav class="text-white bg-dark mb-4">
    <div class="container">
      Navigation Bar Here
    </div>
  </nav>
  <article class="container">
    <header class="bg-light mb-4 p-4 p-md-5 border rounded">
      <h1>Article Title</h1>
      <p>Author, date</p>
    </header>
    <div class="row g-5 grid-75-25">
      <main class="col-md-9">
        <h2 id="topic-1">Article Topic 1</h2>
        <p>Put your topic summary here.</p>
        <h3 id="subtopic-1a">Subtopic 1A</h3>
        <p>Put your subtopic text here.</p>
        <h3 id="subtopic-1b">Subtopic 1B</h3>
        <p>Put your next subtopic text here.</p>
        <!-- START ELEMENT EXAMPLES -->
        <hr>
        <h2 id="elems">HTML Element Examples</h2>
        <p>Below are common HTML elements to use in articles.</p>
        
        <h3 id="elems-image">Images</h3>
        <figure>
          <img class="ms-auto" src="../images/placeholder-x.png" alt="placeholder">
          <figcaption>Image Caption</figcaption>
        </figure>
        <!-- END ELEMENT EXAMPLES -->     
      </main>
      <!-- START SIDEBAR MENU -->
      <nav class="col-md-3">
        <div class="bg-light p-4 mb-3 border rounded">
          <h5>Table of Contents (sidebar)</h4>
          <ul>
            <li>Link to heading id "topic-1"</li>
            <li>Link to heading id "subtopic-1a"</li>
            <li>Link to heading id "subtopic-1b"</li>
          </ul>
        </div>  
      </nav>
      <!-- END SIDEBAR MENU -->
    </div>
  </article>
  <footer class="bg-light mt-3 py-4 border-top">
    <div class="container">
      Footer Here
    </div>
  </footer>
</body>

Set style rules

In the styles.css stylesheet, let's go through the style rules for each class.

Border Box
styles.css
html { box-sizing: border-box; }
*, *::before, *::after { box-sizing: inherit; }
body { margin: 0;}

We'll start by setting the box-sizing property to border-box.
Setting CSS properties on the html element changes the root property value.
By default, the width and height properties only affect the element content.
Changing box-sizing to border-box adds padding and border to the width and height properties. Margin is not included. This should make it easier to calculate spacing.

By default, browsers apply an 8px margin to the body. We'll change that to body { margin: 0;} before setting the container class margins.

Now our content will go right up against the edges of the browser window.

Container
We added a class called container to the nav, main, and footer elements. 

To add space between the left and right browser window edges and our content, add the below style rule to the stylesheet. 

.container {
  width: 100%;
  padding-right: .75rem;
  padding-left: .75rem;
  margin-right: auto;
  margin-left: auto;
}

  • Setting width to 100% means the elements with this class will take up 100% of the width of the parent element. In this case the parent element is body, so the nav, main and footer elements will all take up 100% of the width of the browser window. 
  • Setting right and left padding to .75rem will add space between our content and the right and left edges of the browser. 
    • Since the root font-size is 16px, this will add 12px of right and left padding. 
    • We set a background color to the nav and footer elements. Background color applies to both the content and padding space, but not to margin. So the nav and footer background color will go all the way to the right and left browser edges. 
  • Setting margin to auto will automatically calculate the margin value to be the total available space, if any. Setting it on both left and right will center the element if there is any available space for margin. On our simple Blog Site there is no available margin space so this currently has no impact.

Min/max size
You can set a minimum or maximum width or height.
If we add the below properties to our container class, then:
  • If the user widens the browser window, the content will stop widening after 1140px. 
  • If the user contracts the browser window, the container element won't shrink smaller than 800px wide.

.container {
  ...
  min-width: 800px;
  max-width: 1140px;
}

Remove the above from the stylesheet. We will be using media queries to set the max-width, and will just use the browser's minimum width.

Media Queries
Use media queries to set different style rules depending on user device characteristics (see CheatSheet: Layout category: Media Queries).

The format for a media query is: @media (property: value) { /* style rules */ } 

Put a CSS condition in parentheses. If the condition is true then apply the style rule in curly braces.

Our container class does not include a max-width property. 
We will use media queries to add a max-width property to the container class with a different value depending on the browser window width.

To do that, add the below media queries to the stylesheet: 
@media (min-width: 576px) {
  .container { max-width: 540px; }
}
@media (min-width: 768px) {
  .container { max-width: 720px; }
}
@media (min-width: 992px) {
  .container { max-width: 960px; }
}
@media (min-width: 1200px) {
  .container { max-width: 1140px; }
}

  • If the browser window width is less than 576px, then none of the above apply.
  • If it is 576px or wider then we set the container class's max-width to 540px.
  • If it is 768px or wider then we reset the container class's max-width to 720px.
  • If it is 992px or wider then we reset the container class's max-width to 960px.
  • If it is 1200px or wider then we reset the container class's max-width to 1140px.

Now, if the user drags the edge of the browser window to make it wider or narrower, you will see the content width change when it hits the specified minimum widths.

Make the grid layout responsive
When we set up the grid layout in the last tutorial, we split the pages into columns.

On the index page we could display the article summaries and the about section side by side.
On the article template page, we display the article and the table of contents side by side. 

But if the page is displayed on a small screen like a smart phone, there isn't enough room to display them side by side. 

So lets make the grid responsive by placing the grid CSS into the below media query:
stylesheets/styles.css
@media (min-width: 992px) {
  .container { max-width: 960px; }
  /* -- GRID -- */
  .row { display: grid; }
  .grid-67-33 { grid-template-columns: 2fr 1fr; }
  .grid-75-25 { grid-template-columns: 3fr 1fr; }
  .g-5 {grid-gap: 3rem; gap: 3rem; } 
  .width-67 { width: 67%; }
}

Now the grid classes will only apply if the browser window width is 992px or wider. That means smart-phones and tablets won't spit the page into two columns. Instead they will be in one column, and the About section will display below the article summaries, and the table of contents will display below the article. 


Padding and margin utility classes

Bootstrap has a series of utility classes to add padding and margin to an element. 
Example: class mt-1 sets the CSS style rule to .mt-1 { margin-top: .25rem; }
They use a letter system where the first letter indicates padding or margin:
  • p is for padding
  • m is for margin

The second letter indicates the side:
  • t is for top. Example: .mt-1 { margin-top: .25rem; }
  • b is for bottom. Example: .mb-1 { margin-bottom: .25rem; }
  • s is for start, which is left. Example: .ms-1 { margin-left: .25rem; } 
    • But if the language set in the browser is one that reads from right to left like Hebrew, Arabic and Farsi, then start is right.
  • e is for end, which is right. Example: .me-1 { margin-right: .25rem; } 
    • For languages that read right to left, end is left.
  • x is for right and left. Example: .mx-1 { margin-left: .25rem; margin-right: .25rem; } 
  • y is for top and bottom. Example: .my-1 { margin-top: .25rem; margin-bottom: .25rem; } 
  • If there is no second letter, then it applies to all 4 sides. Example: .m-1 { margin: .25rem; } 

The dash followed by a number indicates length value. Bootstrap uses a convention of numbers 0-5.
  • 0 is 0px. Example: .m-0 { margin: 0 !important; }
  • 1 is .25rem (4px). Example: .m-1 { margin: .25rem !important; }
  • 2 is .5rem (8px). Example: .m-2 { margin: .5rem !important; }
  • 3 is 1rem (16px). Example: .m-3 { margin: 1rem !important; }
  • 4 is 1.5rem (24px). Example: .m-4 { margin: 1.5rem !important; }
  • 5 is 3rem (48px). Example: .m-5 { margin: 3rem !important; }

Now add margin and padding style rules for the margin and padding utility classes used in the Blog Site.

.mt-0 { margin-top: 0px!important }
.mt-3 { margin-top: 1rem!important; }
.mb-2 { margin-bottom: .5rem!important; }
.mb-3 { margin-bottom: 1rem!important; }
.mb-4 { margin-bottom: 1.5rem!important; }
.ms-2 { margin-left: .5rem!important; }
.me-2 { margin-right: .5rem!important; }
.ms-auto { margin-left: auto !important; }
.my-3 { margin-top: 1rem!important; margin-bottom: 1rem!important; }
.px-0 { padding-left: 0px!important; padding-right: 0px!important; }
.p-4 { padding: 1.5rem!important; }
.py-4 { padding-top: 1.5rem!important; padding-bottom: 1.5rem!important; }


Border

You can add or modify an element's borders with CSS. There are three border properties:
  • width Default is 3px. Set a different width example: border-width: 1px;
  • border-style Default is none. Other values are solid, hidden, dotted, dashed, double, groove, ridge, inset, outset. Set a different width example: border-style: solid;
  • color Default is black. Set a different color example: border-color: grey;

There is a shortcut to set width border-style and color in one declaration: border: 1px solid black; 

To set a border on a specific side, use border-top, border-right, border-bottom, border-left.
Example: border-bottom: 3px double grey; sets a border just on the bottom.

You can round the corners with the border-radius property: border-radius: .25rem; This adds a radius of 4px on each corner.

Add the below style rules to the styles.css stylesheet.
.border { border: 1px solid #dee2e6!important; }
.border-top { border-top: 1px solid #dee2e6!important; }
.border-bottom { border-bottom: 1px solid #dee2e6!important; }
.rounded { border-radius: .25rem!important;}

Save the file, and look at the results in the browser.
  • The nav, main, and footer elements have proper spacing to the left and right.
  • The featured article, and About sections are in boxes with colored background, padding, margin, borders and rounded corners.
  • The article summaries have a bottom margin and border.
Open CheatSheet Back To List Next Tutorial