One place for hosting & domains

      How To Use the Display Property to Manipulate the Box Model in CSS


      The author selected the Diversity in Tech Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      HTML and CSS work together to render visual elements of a web page in the browser. HTML elements carry computational and hierarchical meaning and have default styles the browsers apply to these elements. Among these default styles is the display property. The value of this property affects the box model, the mechanism that determines how elements interact with one another on a page. Using the display property, you can efficiently control how an element interacts with the layout of your web page, allowing you to create more flexible solutions for situations like responsive mobile web design.

      In this tutorial, you will work through multiple demos using the display property and learn how it determines flow interactions with other elements. You will begin with the foundational values of display: block and inline. You will then use the combination value of inline-block to learn about the possibilities of the inline- prefixed values. Next, you will learn about the power and danger of using the none value. Lastly, you will use a max-width media query to transform a table into a display: block view on a small screen.

      Prerequisites

      Setting Up the Initial HTML and CSS files

      To begin, you will set up the HTML and CSS files that you will use throughout the tutorial. You will also explore the default display values of text-containing elements.

      Start by opening index.html in your text editor and adding the following code to your file:

      index.html

      <!doctype html>
      <html>
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <title>The Terrestrial Planets</title>
          <link href="https://www.digitalocean.com/community/tutorials/styles.css" rel="stylesheet" />
        </head>
        <body>
        </body>
      </html>
      

      This code sets up the framework necessary for every HTML document. The information contained in the <head> element defines the page’s name in the <title> element and where to load the stylesheet, which is determined in the <link> element. The <meta> tags define the character encoding and small screen device handling, respectively. The main content of the page will be added inside the <body> tags throughout the tutorial.

      Next, inside the <body> element, create a <main> element with a class attribute set to content-width. You will use this element to handle the layout of the content within the page. Inside the <main> element, create an <h1> tag pair followed by a <p>. Within the <h1> and <p> elements, add the content shown in the following code block:

      index.html

      <!doctype html>
      <html>
        <head>
          ...
        </head>
        <body>
          <main class="content-width">
            <h1>The Terrestrial Planets of the Solar System</h1>
      
            <p>
              The four inner planets of the Solar System consist of Mercury, Venus, Earth, and Mars. These planets are known as terrestrial due to their hard, rocky surface. Compared to the gaseous planets of the outer solar system, the inner terrestrial planets are significantly smaller in size. Depending on tectonic activity and presence of liquids these planets will have features such as canyons, mountains, and volcanoes on their surface.
            </p>
          </main>
        </body>
      </html>
      

      Highlighted code, like that in the previous code block, is used throughout this tutorial to emphasize changes to the code.

      Save your changes to index.html, then create a new file called styles.css and open it in your editor as well.

      In your styles.css file, you will add selectors for the elements you created in index.html. Create a selector for body and .content-width, then add the styling properties as demonstrated in the following code block:

      styles.css

      body {
        margin: 0;
        font-family: sans-serif;
        line-height: 1.5;
        color: hsl(215, 5%, 20%);
        background-color: hsl(215, 5%, 98%);
      }
      
      .content-width {
        margin: 2rem auto;
        width: 90%;
        max-width: 40rem;
      }
      

      The styles for the body element reset some default layout and text styling with the margin, font-family, and line-height properties. The color and background color add a dark-gray blue and a light-gray blue to the page. The .content-width properties will keep it centered to the page, taking up 90% of the screen width until it reaches a maximum size of 40rem, or 640px.

      Next, add some font styling to make the text more legible:

      styles.css

      ...
      .content-width {
        margin: 2rem auto;
        width: 90%;
        max-width: 40rem;
      }
      
      h1 {
        font-size: 2rem;
        font-weight: 400;
        line-height: 1.2;
      }
      
      p {
        font-size: 1.125rem;
      }
      

      The h1 properties define the size and weight of the text and bring the line-height property down to a better spacing for headings. Lastly, the p element selector bumps up the font-size to 1.125rem, or 18px.

      Save your changes to styles.css, then open your web browser. Open index.html in the browser by dragging the file into the browser window or using the browser’s Open File option. The browser will render the HTML and CSS code to produce a page like the following image:

      Large header text and smaller paragraph text in a dark blue-gray color on a light gray background.

      So far, the HTML elements that you have worked with are known as block elements. These are elements that create defined areas of content that take up the full width of the parent container. Additionally, block elements are usually rendered by themselves on a new line. This means that added block elements stack toward the end of the page. For a top-to-bottom, left-to-right language like English, block elements stack toward the bottom of the browser window.

      Next, you will add inline elements, which are elements that exist within the flow of text content. Since inline elements do not take up the entire width of their parent, and since they are not rendered on their own lines, they are added in the direction of the text flow. For English, this is a left-to-right direction.

      Where block elements define the meaning and group of content, like a paragraph, inline elements provide context about a word or group of words, such as an emphasis.

      Return to index.html in your text editor. In the second sentence, wrap the word terrestrial in the emphasis tag, <em>. Then, in the third sentence, wrap the phrase gaseous planets in an anchor tag, <a>. In the opening <a> tag add an href attribute with a value of https://en.wikipedia.org/wiki/Giant_planet. This will link to the Wikipedia page on the topic. The highlighted HTML in the following code block demonstrates how this is set up:

      index.html

      ...
      <p>
        The four inner planets of the Solar System consist of Mercury, Venus, Earth, and Mars. These planets are known as <em>terrestrial</em> due to their hard, rocky surface. Compared to the <a href="https://en.wikipedia.org/wiki/Giant_planet">gaseous planets</a> of the outer solar system, the inner terrestrial planets are significantly smaller in size. Depending on tectonic activity and presence of liquids these planets will have features such as canyons, mountains, and volcanoes on their surface.
      </p>
      ...
      

      Save these additions to index.html then, return to styles.css in your text editor. To demonstrate the difference between block and inline elements, create an a element selector. Inside the selector add the display property set to block, as demonstrated in the following code block:

      styles.css

      ...
      p {
        font-size: 1.125rem;
      }
      
      a {
        display: block;
      }
      

      Save your change to styles.css, then return to the page in your web browser. Refresh the page to load the latest version of your code. The page demonstrates the key difference between a block and an inline element, as the link set to display: block now occupies its own line. This is demonstrated in the following image:

      Large header text and smaller paragraph text in a dark blue-gray color on a light gray background with a blue underlined text breaking up the paragraph into two sections.

      The primary difference between a block and an inline value is that a block breaks the current content flow while inline maintains it. Additionally, if a width property were applied to the a selector, it would not change the layout. When the content flow is disrupted by a block element, it remains broken, and the width always takes up the entire parent container width.

      inline and block are the most common browser default values. While the display property has many values, with a few exceptions, all remaining elements use one of these two values.

      Now that you have explored the differences between block and inline, return to styles.css in your text editor. In the a selector, remove the display: block and replace it with a color property with a value of hsl(215, 80%, 50%), which is a richer version of the blue used on the body. Then create an a:hover selector with a text-decoration property set to none. This will remove the underline when the link is hovered. The highlighted CSS in the following code block shows how this is written:

      styles.css

      ...
      a {
        color: hsl(215, 80%, 50%);
      }
      
      a:hover {
        text-decoration: none;
      }
      

      Save your changes to styles.css and refresh index.html in your web browser. The link will once again be inline with the text and will now be a lighter blue color, as shown in the following image:

      Large header text and smaller paragraph text in a dark blue-gray color on a light gray background with a blue underlined link.

      In this section, you set up the HTML and CSS files you will use throughout the tutorial. These files will be amended and modified regularly, so keep both files open in your text editor and remember to save regularly. You also learned about the default display values, inline and block, and changed the value of an inline element to block. In the next section, you will use the inline-block value, which combines the capabilities of inline and block.

      Using the inline-block Value

      Next, you will create a button element with a customizable width, rather than a button that takes up the whole width of the parent container. To do this, you will use the inline-block value, which maintains box model properties of the block value like margin and padding while also having the content flow properties of the inline value.

      The inline- prefix is available on several display values, including inline-flex, inline-grid, and inline-table. The inline-block value defines the box model of the element as a block, but it does not disrupt the content flow. Additionally, inline-block does not take up the full parent width, as block does. Instead, the inline-block element condenses down to only the width of its content. For shorter content, such as a button, this makes for a useful resizing of the element with block box model properties, such as margin.

      To begin working with inline-block, open index.html in your text editor. After the closing <p> tag, add an <a> tag with a class attribute set to button and an href attribute set to https://en.wikipedia.org/wiki/Terrestrial_planet. Inside that tag, add the text Learn more on Wikipedia. The highlighted HTML in the following code block demonstrates how this is written:

      index.html

      <div class="content-width">
        <h1>The Terrestrial Planets of the Solar System</h1>
      
        <p>
          ...
        </p>
      
        <a href="https://en.wikipedia.org/wiki/Terrestrial_planet" class="button">Learn more on Wikipedia</a>
      </div>
      

      Save your changes to index.html, then open styles.css in your text editor.

      In your styles.css file, add a class selector for .button. This will style the link you created in your index.html file. By default, an <a> has a display value of inline. For this step, change the display value to block for the button class, then add the additional highlighted styles from the following code block:

      styles.css

      ...
      a:hover {
        text-decoration: none;
      }
      
      .button {
        display:block;
        padding: 0.5rem 1.25rem;
        text-align: center;
        text-decoration: none;
        color: hsl(215, 20%, 95%);
        background: linear-gradient(to bottom, hsl(215, 80%, 60%), hsl(215, 80%, 40%));
      }
      

      The additional styles added to the .button element add padding, center the text, and remove the link underline. Additionally, the styles add a blue gradient of the same hue as the earlier versions of this blue with a near white text color.

      Save these changes to the styles.css, then return to your browser and refresh index.html. The button will fill the full width of the content area with a blue gradient. The following image shows how this will render in the browser:

      Large header text and smaller paragraph text in a dark blue-gray color on a light gray background with a blue button below the paragraph with white text. The button is as wide as the paragraph.

      Next, you will change the block value for the display property to inline-block. Return to styles.css in your text editor and change the display property value from block to inline-block, as highlighted in the following code block:

      styles.css

      ...
      .button {
        display: inline-block;
        padding: 0.5rem 1.25rem;
        text-align: center;
        text-decoration: none;
        color: hsl(215, 20%, 95%);
        background: linear-gradient(to bottom, hsl(215, 80%, 60%), hsl(215, 80%, 40%));
      }
      

      Save these changes to styles.css and then refresh index.html in your web browser. The width of the button has condensed from extending the full width of its parent to being just as wide as its content, plus the padding value. The following image demonstrates how the inline-block element renders in the browser:

      Large header text and smaller paragraph text in a dark blue-gray color on a light gray background with a blue button below the paragraph with white text. The button is only as wide as the text inside the button.

      Finally, return to styles.css to add in some last styling for the button. You will add styles to apply a 3D effect to the button by adding a border-radius, border, text-shadow, and box-shadow. Also, create a .button:hover selector and add a box-shadow and linear-gradien() that make a darker hover state. The highlighted CSS in the following code block show how to write these styles:

      styles.css

      ...
      .button {
        display: inline-block;
        padding: 0.5rem 1.25rem;
        text-align: center;
        text-decoration: none;
        color: hsl(215, 20%, 95%);
        background: linear-gradient(to bottom, hsl(215, 80%, 60%), hsl(215, 80%, 40%));
        border-radius: 0.25rem;
        border: 1px solid hsl(215, 80%, 35%);
        text-shadow: 0 -1px hsl(215, 80%, 35%);
        box-shadow: 0 1px hsl(215, 80%, 70%) inset;
      }
      
      .button:hover {
        box-shadow: 0 1px hsl(215, 80%, 60%) inset;
        background: linear-gradient(to bottom, hsl(215, 80%, 50%), hsl(215, 80%, 30%));
      }
      

      Save your changes to styles.css and then refresh the page in your web browser. Visually, the button now has more definition and depth, as shown in the following image:

      Blue gradient button with white text and a dark border.

      In this section, you used the inline-block value on a link to create a button that is large and clickable, but only as wide as the link’s text. You also learned how there are other inline- prefixed display values that allow for various display types that do not disrupt the content flow. In the next section, you will continue changing display values by switching table elements to block.

      Changing a Table to Use display: block

      Next, you will convert a whole table to use the display: block property value. A table requires HTML specific to the table element, and each child element of the table has its own default display value. For example, the <table> element has a display value of table, and the table cell, <td>, has a display value of table-cell. There can be many reasons why a table might need to change its display value, but most often it is for a small-screen device solution where the table doesn’t fit well.

      To begin working with a table’s display property, open index.html in your text editor. After the button link, add the highlighted HTML from the following code block:

      index.html

      ...
      <a href="https://en.wikipedia.org/wiki/Terrestrial_planet" class="button">Learn more on Wikipedia</a>
      
      <table>
        <caption>
          Terrestrial Planets Statistics
        </caption>
        <thead>
          <tr>
            <th>Name</th>
            <th>Radius</th>
            <th>Moons</th>
            <th>Gravity</th>
            <th>Wikipedia</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <th>Mercury</th>
            <td>2,439.7 km</td>
            <td>0</td>
            <td>3.7 m/s<sup>2</sup></td>
            <td>
              <a href="https://en.wikipedia.org/wiki/Mercury_(planet)" class="button">
                Learn More
              </a>
            </td>
          </tr>
          <tr>
            <th>Venus</th>
            <td>6,051.8 km</td>
            <td>0</td>
            <td>8.87 m/s<sup>2</sup></td>
            <td>
              <a href="https://en.wikipedia.org/wiki/Venus_(planet)" class="button">
                Learn More
              </a>
            </td>
          </tr>
          <tr>
            <th>Earth</th>
            <td>6,371.0 km</td>
            <td>1</td>
            <td>9.80665 m/s<sup>2</sup></td>
            <td>
              <a href="https://en.wikipedia.org/wiki/Earth_(planet)" class="button">
                Learn More
              </a>
            </td>
          </tr>
          <tr>
            <th>Mars</th>
            <td>3,389.5 km</td>
            <td>2</td>
            <td>3.72076 m/s<sup>2</sup></td>
            <td>
              <a href="https://en.wikipedia.org/wiki/Mars_(planet)" class="button">
                Learn More
              </a>
            </td>
          </tr>
        </tbody>
      </table>
      ...
      

      This table HTML creates a table called “Terrestrial Planets Statistics” by putting that name in the <caption> element, a necessary component of screen-reader accessible tables. Then the HTML creates a five-column table consisting of a header row and four data rows.

      Next, to add some visual styles to the table, open styles.css in your text editor. You will create a visual style that makes the caption like a header for the table. The table header row will become more distinct with a dark background, and you will create a zebra stripe effect with alternating background colors on the data rows. The highlighted CSS in the following code block demonstrates how these styles are written:

      styles.css

      ...
      table {
        border-collapse: collapse;
        width: 100%;
        margin: 3rem 0;
      }
      
      caption {
        font-size: 1.5rem;
        font-weight: 700;
        color: hsl(215, 25%, 25%);
        text-align: left;
        margin-bottom: 0.5em;
      }
      
      tr {
        text-align: center;
      }
      
      thead > tr {
        color: hsl(215, 25%, 100%);
        background-color: hsl(215, 80%, 20%);
      }
      
      tbody > tr:nth-child(even) {
        background-color: hsl(215, 50%, 93%);
      }
      
      tbody th {
        font-size: 1.125rem;
      }
      
      td, th {
        padding: 0.5rem;
      }
      

      Save your changes to styles.css and open index.html in your web browser. The table is styled with clear data and alignment, as shown in the following image:

      Table grid of data containing information about the four terrestrial planets.

      Open your local version of index.html on a smart phone, or scale your browser’s window down to about the size of a smart phone. The table will eventually start going off screen and will only be viewable by scrolling horizontally, as demonstrated in the following image:

      A phone containing a table going off screen, cutting off informations.

      This is a situation where changing the display value of the table elements can help provide a better viewing experience for those on smaller screens.

      Return to styles.css in your text editor and create a media query set to a max-width of 60rem. Normally, you would use min-width instead of max-width in your media queries to follow a mobile first design flow. However, since you will only change the style on small screens and then return to the browser default at a given screen size, in this example situation max-width requires the least work. Inside the media query, create a group combinator consisting of table, caption, thead, tbody, tr, th, and td. Then set the display property to block, as highlighted in the following code block:

      styles.css

      @media (max-width: 60rem) {
        table,
        caption,
        thead,
        tbody,
        tr,
        th,
        td {
          display: block;
        }
      }
      

      Save your changes to styles.css and return to index.html on your smartphone or in a small-size browser window. All the contents of the table are now stacked in one large column, with each row’s contents grouped together. The following image shows how this is rendered on a mobile phone:

      Contents of a table in a vertical stack.

      This change to the table’s display value creates two issues. The first is that the browser no longer recognizes the table as a table, and therefore will not be read to a screen reader as a table. The second is that some of the contents and styles are now not providing useful information. For starters, the table headers no longer provide visual connection to the data types. Secondly, the zebra stripes don’t provide as much information in this scenario.

      Return to styles.css in your text editor. First, remove thead from the group combinator. Next, create a new selector for the thead element and give it a display property set to a value of none. The display: none value completely removes an element visually from rendering in the browser. It is important to know that the none value also removes the element from the screen reader DOM, so the element is hidden from all users. The highlighted CSS in the following code block shows how this is set up:

      styles.css

      @media (max-width: 60rem) {
        table,
        caption,
        tbody,
        tr,
        th,
        td {
          display: block;
        }
      
        thead {
          display: none;
        }
      }
      

      Next, to begin addressing the style changes, start by adding a text-align property to the large group combinator with a value of left. Next, duplicate the selector used for the zebra stripes, tbody> tr:nth-child(even), and set the background-color to transparent. This will remove the zebra stripe effect on screens and windows smaller than 60rem, or 960px, wide. Then, make the Learn More button work as a full-width button on small screens. Create a table .button descendant selector with the display property set to block, which will cause the button to fill the width of the container. The highlighted CSS in the following code block illustrates how this looks:

      styles.css

      @media (max-width: 60rem) {
        table,
        caption,
        tbody,
        tr,
        th,
        td {
          display: block;
          text-align: left;
        }
      
        thead {
          display: none;
        }
      
        tbody > tr:nth-child(even) {
          background-color: transparent;
        }
      
        table .button {
          display: block;
        }
      }
      

      Save your changes to styles.css in your text editor and then refresh index.html in your browser. On small-screen devices, the content of the tables are now all left-aligned with the button spanning the width of the content. The following image shows how this is rendered in Safari on a mobile phone:

      A series of bold heading text with data information and a button for each group.

      In this section, you converted a table to a block element to make it more visually usable when the screen or browser window small. In the last section, you will improve the accessibility of the table both for sighted users and those using screen readers.

      Adding Small-Screen Context Elements

      Now that you have changed the display values for the table elements on a small screen, you can add some enhancements to make this view as useful as the large screen version. You will add some HTML that will help make the information more understandable on small screens. Then you will provide styling specifically for the small screen experience of the table information.

      To begin, open index.html in your text editor. To provide the table’s contextual information lost by hiding the thead element, you will add that header value to each cell inside a <span> element. For example, you will add <span>Radius: </span> before the value in the column containing the Radius information for the planet in each <td> element. Additionally, each <span> element will have a class attribute set to a value of label, so these elements can be quickly styled. The highlighted HTML in the following code block shows how to write the markup:

      index.html

      ...
        <tbody>
          <tr>
            <th>Mercury</th>
            <td><span class="label">Radius: </span>2,439.7 km</td>
            <td><span class="label">Moons: </span>0</td>
            <td><span class="label">Gravity: </span>3.7 m/s<sup>2</sup></td>
            <td>
              <a href="https://en.wikipedia.org/wiki/Mercury_(planet)" class="button">
                Learn More
              </a>
            </td>
          </tr>
          <tr>
            <th>Venus</th>
            <td><span class="label">Radius: </span>6,051.8 km</td>
            <td><span class="label">Moons: </span>0</td>
            <td><span class="label">Gravity: </span>8.87 m/s<sup>2</sup></td>
            <td>
              <a href="https://en.wikipedia.org/wiki/Venus_(planet)" class="button">
                Learn More
              </a>
            </td>
          </tr>
          <tr>
            <th>Earth</th>
            <td><span class="label">Radius: </span>6,371.0 km</td>
            <td><span class="label">Moons: </span>1</td>
            <td><span class="label">Gravity: </span>9.80665 m/s<sup>2</sup></td>
            <td>
              <a href="https://en.wikipedia.org/wiki/Earth_(planet)" class="button">
                Learn More
              </a>
            </td>
          </tr>
          <tr>
            <th>Mars</th>
            <td><span class="label">Radius: </span>3,389.5 km</td>
            <td><span class="label">Moons: </span>2</td>
            <td><span class="label">Gravity: </span>3.72076 m/s<sup>2</sup></td>
            <td>
              <a href="https://en.wikipedia.org/wiki/Mars_(planet)" class="button">
                Learn More
              </a>
            </td>
          </tr>
        </tbody>
      ...
      

      Save your changes to index.html and return to your browser to examine the small-screen view. The contextual information around what each data point means is now visually recognizable. The following image shows how this will render in the browser:

      A series of bold heading text with contextual data information and a button for each group.

      Next, return to styles.css in your text editor. These labels will be present on larger screens when they are no longer necessary, so they will need some styling to fix this issue. Due to the max-width media query approach, this means that the default styles for .label outside the query need to be set to display: none in order to hide the content on large screens. Then inside the media query, create a .label selector with a display property set to inline, since it should be in the content flow containing the value. To create a visual separation between the label and data point, add a font-weight property set to 700. The highlighted CSS in the following code block demonstrates how and where to apply these additions:

      styles.css

      ...
      td, th {
        padding: 0.5rem;
      }
      
      .label {
        display: none;
      }
      
      @media (max-width: 60rem) {
        ...
        .label {
          display: inline;
          font-weight: 700;
        }
      }
      

      Save your changes to styles.css and once again return to your browser and refresh index.html. The browser will render the labels as inline content that is bold, as shown in the following image:

      A series of bold heading text with bold contextual labels and data information and a button for each group.

      While still in your web browser on a large screen, expand the window out until the table returns to the tabular style. The labels are now hidden providing distinctive visual and accessible information for each scenario. The following image shows how the large screen version of the table is now rendered:

      Table grid of data containing information about the four terrestrial planets.

      Finally, you will provide additional styling for each table row that will make them appear as their own little tables.

      Open styles.css in your text editor. Inside the media query, add a tbody th descendant selector and add the color properties and values from the thead > tr selector. This will give the same dark blue background and near-white text color for each planet name. Then, add a border-radius property set to 0.5rem 0.5rem 0 0 to create a rounded top to the heading. The highlighted CSS of the following code block shows how to style the planet name:

      stlyes.css

      ...
      @media (max-width: 60rem) {
        ...
        .label {
          display: inline;
          font-weight: 700;
        }
      
        tbody th {
          color: hsl(215, 25%, 100%);
          background-color: hsl(215, 80%, 20%);
          border-radius: 0.5rem 0.5rem 0 0;
        }
      }
      

      Next, you will add some definition to the datasets and give some spacing between each grouping. First, create a tbody > tr selector inside the media query with a border property set to 1px solid hsl(215, 80%, 20%). Then add a border-radius property with a value of 0.5rem, which will round the corner of all sides of the container. Lastly, create a tbody > tr + tr adjacent sibling combinator, with a margin-top property set to 1rem, which will give space between each group of data. The highlighted CSS in the following code block demonstrates how this is written:

      stlyes.css

      ...
      @media (max-width: 60rem) {
        ...
        tbody th {
          color: hsl(215, 25%, 100%);
          background-color: hsl(215, 80%, 20%);
          border-radius: 0.5rem 0.5rem 0 0;
        }
      
        tbody > tr {
          border: 1px solid hsl(215, 80%, 20%);
          border-radius: 0.5rem;
        }
      
        tbody > tr + tr {
          margin-top: 1rem;
        }
      }
      

      Finally, you will add in a zebra stripe effect specifically for each td element. This is done by creating a td:nth-child(even) pseudo-class selector. Then use the same background-color property and value from before, as highlighted in the following code block:

      stlyes.css

      ...
      @media (max-width: 60rem) {
        ...
        tbody > tr + tr {
          margin-top: 1rem;
        }
      
        td:nth-child(even) {
          background-color: hsl(215, 50%, 93%);
        }
      }
      

      Save your changes to styles.css and open index.html on a small-width browser or smartphone. Each row from the table will now appear as though it were a table with a header, data points, and a button to learn more. The following image shows how this is rendered in on a smartphone browser:

      Groups of data blocks, with the header in white on a dark background, and data points in alternating rows of light blue and white background.

      In this last section, you used the display property to show and hide pertinent information that was contextual to the viewing scenario of a small-screen device. You also provided styling to the small-screen table to make it more accessible and usable.

      Conclusion

      There are many possibilities when working with the display property. In this tutorial, you learned about the default values of block and inline. You changed an <a> element to inline-block, which gave it a special combination of both block and inline. You then changed all the elements of a <table> to be block on a small screen and set them to return to their default table display values on a large screen. Lastly, you used the none value to hide content when and where necessary to users of all abilities. The display property is a powerful feature and has even more values available to further manipulate how the box model functions and affects elements.

      If you would like to read more CSS tutorials, try out the other tutorials in the How To Style HTML with CSS series.



      Source link

      How To Work with the Box Model in CSS


      The author selected the Diversity in Tech Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      The box model is the ruleset a browser uses to determine an element’s size and how it interacts with other elements. The contents of the HTML element, as well as several CSS properties, all contribute to the calculations a browser uses to turn HTML and CSS code into a final, rendered web page. Knowing how the box model works and how to manipulate it effectively can be the difference between a well-aligned design and a web page with unwanted horizontal scrolling and extra space between content. Understanding how the box model works will help you write CSS more efficiently and find solutions to rendering issues in the browser.

      Note: Most HTML elements fall in to one of two categories of boxes, an inline or a block. A <span> element is a generic inline element, as it stays inline with the text content. The <div> element, is a generic block element. This tutorial will focus on how the box model affects block elements, as it is the broadest use of the box model ruleset.

      Be aware that changes to the display property can result in changes to how the box model functions in ways outside of the goals of this tutorial, especially when working with tables, Flexbox, and CSS Grid.

      In this tutorial, you will use the margin, padding, border, width, and height properties, which are the primary properties the box model uses. You will also work with the box-sizing properties to understand how the box model can be changed. Lastly, you will use your browser’s developer tools to inspect the box model.

      Prerequisites

      In this section, you will set up the HTML base for use throughout the tutorial. You will also access your browser’s developer tools and begin to use them to help identify the properties that make up the box model.

      To start, open up index.html in your text editor and add the following HTML to the file:

      index.html

      <!doctype html>
      <html>
          <head>
              <title>Box Model</title>
              <link href="https://www.digitalocean.com/community/tutorials/styles.css" rel="stylesheet" />
          </head>
          <body>
          </body>
      </html>
      

      The HTML includes a reference to a styles.css file in the <link /> tag. Go ahead and create that file; you will begin to edit that in the next section.

      Next, you will need content to apply styles to and start to work with the box model. In the next code block, add the highlighted code within the <body> tag. Highlighted code like this will be used throughout the tutorial to identify changes and additions to the code. For the content, create two <div> elements and fill them with the following two quotes from Alice’s Adventures in Wonderland, by Lewis Carol:

      index.html

      ...
      <body>
          <div>
              Alice had begun to think that very few things indeed were really impossible.
          </div>
      
          <div>
              "Begin at the beginning," the King said gravely, "and go on till you come to the end: then stop."
          </div>
      </body>
      ...
      

      Next, open up index.html in your browser of choice and open the browser’s developer tools. This can often be accomplished by right-clicking on the page and selecting Inspect or Inspect Element. Once you have opened the developer tools, inspect the first <div> element. In both Firefox and Chrome a visual diagram of the box model will be visible. The following is what you would find in the Firefox developer tools:

      Diagram of the box model with defined boxes from the outer most to inner most as margin, border, and padding, all set to 0 with a computed width and height of 970 by 19.

      Looking closer at the box model visualization from Firefox, the properties that make up the box model are show from the center outward as width, height, padding, border, and margin. These five properties make up the box model and provide the dimensional characteristics of the element. As you work with each of the properties and refresh your changes in the browser, be sure to keep the developer tools open to reference this box model visualization of your elements.

      In this section, you set up your HTML for the tutorial, opened up your browser’s developer tools, and accessed the box model visualization guide. In the next section you will begin writing CSS for the border property, which will provide a beginning visual style of the box model for your <div> elements.

      Using the border Property to Visualize Containers

      Now that you have your HTML set up, you will begin applying the properties of the box model, beginning with the border property. In this section you will use the border property to create a visual outline of the <div> elements and see how the property affects the box model.

      The border property is what is known as a shorthand property, as it is a combination of three different properties: border-width, border-style, and border-color. Additionally, there are more border properties that allow for specifying sides, like border-right, which functions like border and is a shorthand combination of border-right-width, border-right-style, and border-right-color.

      border-width, border-style, and border-color also behave as shorthand for their border-top, border-right, border-bottom, and border-left counterparts and apply the styles clockwise from top to right, then bottom, and lastly the left side. For example, border-width: 10px 2px 8px 4px; would apply a 10px border to the top, a 2px border to the right, an 8px border to the bottom, and a 4px border to the left side of the box.

      Open styles.css in your text editor, write a type selector for the div element, and add the border property. For the value, the order is not critical, though a common ordering tends to be width, style, and color. With that in mind, set the value for the border property to 1px solid red:

      styles.css

      div {
          border: 1px solid red;
      }
      

      Save your changes to styles.css then open index.html in your browser. The content of the <div> elements will be wrapped tightly by a thin red line on the perimeter of the box. Between the two lines of text, there will be a thicker border. This occurs when borders from two different elements are set side-by-side, doubling the visual size of the border. The changes will look like this in your browser:

      Two wide rectangles each with text in a black serif font and a thin red border tight against the text.

      With index.html open in your browser, return to the browser developer tools and inspect one of the two <div> elements. Return to the view in the developer tools that shows the box model of the element. In the inner-most box is the width by height of the element, then the padding, and finally the border, noted to have 1 on each side of its box. See the following image from the Firefox developer tools:

      Diagram of the box model with defined boxes from the outer most to inner most as margin set to 0, border set to 1, padding set to 0, and a computed width and height of 970 by 19.

      With the Firefox window set at 986px wide, the width of the inner box of the box model diagram is 968 by 19, but following the diagram is another value that is 970 by 21. This is the computed width and height, which is the final pixel size the browser renders, combining height, width, border, and padding property values together. This difference in size is two more in either dimension, which coincides with the size the border adds to the height and width.

      In this section, you created a border on the <div> elements and saw how this one property affects the computed dimensions of those elements. In the next section, you will expand on your styles by applying inner spacing between the border and the text with the padding property.

      Using the padding Property to Create Space Inside the Container

      Your work with the border property in the previous section gave a visual boundary to the box, but it is very close to the text. Next you will use the padding property to add space on the interior of the box, providing room between the text and box’s border.

      Similar to the border property, the padding property is also a shorthand property. However, padding is shorthand only for the sides, such as the padding-bottom property. When a single value is used, the same value will be applied to all sides. For example, padding: 20px; applies a 20px padding to all sides. When two values are used, then the first value is applied to the top and bottom sides, while the second value is applied to the left and right. For instance, the following padding: 20px 40px; will apply 20px padding to the top and bottom of the box, while the 40px padding is on the left and right sides. This progresses to three values that follow top side, left and right sides, then the bottom. At four values each side is represented as top, right, bottom, and left.

      Open your styles.css file in your text editor and, after the border property, add a padding property with a value of 30px 60px. It is important to put a space between the values, as that is how CSS delineates between multiple values.

      styles.css

      div {
          border: 1px solid red;
          padding: 30px 60px;
      }
      

      Save the latest change to your styles.css file, then return to your index.html file in your browser and refresh the page. The two elements have grown in height and the positioning of the text within the red boxes has shifted down and to the right with extra space below the text. See the following image for what the browser is expected to render:

      Two wide rectangles each with text in a black serif font and a thin red border with space between the text and border.

      Once again, return to the browser developer tools and inspect one of the two boxes. The box model diagram now displays the padding with a 30 on the top and bottom and a 60 on the left and right of the box.

      Diagram of the box model with the padding area of the diagram showing a value of 30 for the top and bottom and a 60 for the left and right.

      You expanded on the complexities of the box model by using the padding property on the <div> elements to give visual space between the border and the text. The box model visual guide in your browser’s developer tools showcased these changes and their effects on the dimensional values displayed. Next you will work with the width and height properties to see how they further affect the box model and how these two properties are changed by the padding property.

      Using the width and height Properties to Limit the Dimension Width

      This section will focus on using defined width and height property values to enforce dimensions on the <div> elements and how those properties are treated in the box model. This section will use pixel units for the width and height values, which is often referred to as fixed dimensions, as well as percent units, which are called fluid dimensions. Unlike the previous two properties, width and height are not shorthand. These apply a defined value. However, setting dimension values with CSS causes a questionable effect that goes back to the early specifications of the language. The width and height are the set dimensions of the visible content before padding and border values are applied. This results in a box that is larger than expected.

      To try out this aspect of the box model, return to the styles.css file in your text editor and add the width property with a value of 250px:

      styles.css

      div {
          ...
          width: 250px;
      }
      

      Save your changes to styles.css, switch to your browser, and refresh index.html. When the page reloads, the content will be much more narrow and wrapped into multiple lines of text. See the following image for how this will appear in your browser:

      Two narrow rectangles each with text in a black serif font and a thin red border with space between the text and border.

      Open up the browser developer tools and inspect one of the two <div> elements. At the center of the box is the value defined by the width property with 250 by 57. However, as the image from the Firefox box model diagram shows, the full width of the element is not 250, but instead 372.

      Diagram of the box model with height and width values set in blue at the center of the box with a width of 250 and black sans-serif text below showing a total width of 372.

      The computed width is determined by the width, which sets the width of the content, followed by the size of the right and left padding values, then by the right and left border-width values. This construct of the box model was devised early in CSS’s development and requires developers to remember that the width and height properties define the dimensions of the content, not the box. This is the default behavior and understanding it as such will help debug problems in the future.

      Instead of using a fixed pixel value for the width, use a fluid percent for the width of 100%. By default, a <div> element extends the full width, but there is a difference here between extending the default full width and having a declared width value of 100%. In your styles.css, change 250px to 100%:

      styles.css

      div {
          ...
          width: 100%;
      }
      

      Save the styles.css file and refresh index.html in your browser. The <div> elements now extend past the viewport’s edge, no matter the size of the window. What is happening is the same as what happened with 250 becoming 372: The full width of the element is now 100% of the available width plus the 122 pixels created with the padding and border values.

      Return to your styles.css file and start by returning the width value to 250px. Next, add a height property and add a value you know will be smaller than the content height. 40px will be sufficient with this content:

      styles.css

      div {
          ...
          width: 250px;
          height: 40px;
      }
      

      Save these changes to the styles.css file and refresh index.html in your browser. The padding will now appear as though it is smaller on the bottom, when in fact the browser is being posed with a dilemma: The height is explicitly set, but the content is larger than the container. The rules the browser follows use the defined height value, and if there were longer content it would extend outside the box.

      With the browser developer tools open, inspect one of the <div> elements and the element will be highlighted in the rendered view. Hover over the padding area of the box model diagram to highlight the padding area of the element. The text content is going into the padding area. See the following image for what you will find in your browser:

      A box with black serif text and red thin border with the spacing between the text and border highlighted purple and the text going in to the bottom portion of the purple area.

      In situations where the content can be variable in length, it is best to avoid a defined height value and instead let the natural height of the content determine the height. Web browsers are built to grow downward and scroll vertically by default, making height the unpredictable and least controllable dimension.

      For this situation, it is best to remove the height attribute altogether. Return to styles.css in your text editor and remove the height property and its value from the file and save your changes. Removing the height value makes the height dependent on the amount of content inside the container. Your CSS will now look like the following:

      styles.css

      div {
        border: solid red 1px;
        padding: 30px 60px;
        width: 250px;
      } 
      

      In this section, you applied the width and height properties to the <div> elements. You discovered how the height property can be difficult to implement due to the flowing nature of web content. Lastly you learned how these dimension properties are applied to an element before the padding property, leading to a larger dimension than intended. Next, you will work with the spacing on the outside of the elements with the margin property.

      Using the margin Property to Create Space Outside the Container

      In this next, section you will use the margin property to apply spacing on the outside of the border to provide spacing between other boxes. The margin property functions similarly to the padding property, with the same long- and short-hand property variations. You will use margin to provide space between the two <div> elements on the page and find how margin differs from padding.

      To start, open styles.css in your text editor, add a margin property to the div type selector and give a value of 20px. This will apply a 20px space on each side of the <div> elements on the page:

      styles.css

      div {
          ...
          margin: 20px;
      }
      

      Save your changes to styles.css then open your browser and load or refresh your index.html file. You will find that the containers have moved to the right and down by 20 pixels. See the following image for what this will look like:

      Two boxes of black serif text with thin red borders with space between each box.

      Take a look at the spacing between the two <div> elements in your browser. The spacing between these is 20px and not 40px, even though there is margin on the bottom of the first <div> and a margin on the top of the second <div>. This is due to a feature of the margin property where adjacent containers overlap their margin properties, taking the value from the larger margin. This may not make sense at first, but it can be helpful to think of the box model as describing a physical object and then defining how much space you want around each one of those objects. For example, if you have 10 people and you want 2 meters of space around each person, the space from one person to the next will be 2 meters, not 4 meters.

      Since the largest margin value is taken as the outside spacing value, change the value of the property so the top and bottom are different. You can do this with the shorthand by making sure the first and third values in the list are different, or by using the margin-top and margin-bottom properties. Keep the top, right, and left values at 20px, but change the bottom value to be 60px.

      styles.css

      div {
          ...
          margin: 20px 20px 60px;
      }
      

      The first value in the shorthand list for a margin defines the top value, the second value defines the right and left, and the third defines the bottom value. Save your changes to styles.css and refresh index.html in your browser. There will now be much more space between the two containers as shown in the following image:

      Two boxes of black serif text with thin red borders with more space between each box.

      Now, inspect one of the two <div> elements with the browser developer tools. Unlike all the other properties, the margin values do not change the computed height or the width of the container:

      Diagram of the box model with margin set in yellow with the number 20 on the top, left, and right side of the box and the number 60 at the bottom.

      The margin property has two special features that padding does not. First, margin accepts negative values, meaning it can move closer to adjacent elements and cause them to overlap. Additionally, the margin property accepts a value of auto, which can be used for centering content. Due to how the browser defaults work, this auto value will only center content horizontally and only if a defined width property is less than 100% of the total available space.

      Return to the styles.css file in your text editor and change the second value of the margin property from 20px to auto:

      styles.css

      div {
          ...
          margin: 20px auto 60px;
      }
      

      Save this change to styles.css and reload index.html in your browser. The <div> containers will now appear horizontally centered, as in the next image:

      Two boxes of black serif text with thin red borders with space between each box centered to the page horizontally.

      You used the margin property in this section to add space between the quotes in the <div> elements. You changed the margin to show how it overlaps and defers to the largest of the adjacent values. Also, you set the value for the margin-left and margin-right properties to auto, which centered the containers. In the last section you will use the box-sizing property to change how the box model behaves and the properties relate to one another.

      Using the box-sizing Property to Change the Box Model Behavior

      In this final section, you will use the box-sizing property, which allows the box model to change how it is formulated. As you have worked with the box model, the width, height, padding, and border properties have contributed to the overall dimensions of the box model. Now with the box-sizing property, you will be able to have the padding and border calculated by the browser to enforce the values set to the width and height values.

      Up to this point, you have worked with the default state of the box-sizing property, which is content-box. The content-box box model determines the width dimension by adding the width, padding-right, padding-left, border-right-width, and border-left-width to be the final computed width value of the box. Likewise, the content-box finds the height dimension by adding the height, padding-top, padding-bottom, border-top-width, and border-bottom-width to arrive at the final computed height value for the box. As discussed in previous sections, this results in a larger than intended box that can disrupt layout and design.

      The alternative to the content-box value for the box-sizing property is border-box. Instead of adding padding and border properties to the declared width and height values to get the computed value, it subtracts the values. This means that the width of a box with a border-box box model is the width property minus the sum of the left and right padding values and the left and right border-width values. The result is a computed width equal to the width property value.

      Open styles.css in your text editor and add a box-sizing property with a value of border-box to the div type selector:

      styles.css

      div {
          ...
          box-sizing: border-box;
      }
      

      Return to your browser and reload index.html. The size of the containers will now be smaller, as the browser is now decreasing the box model’s width so that the computed width of width, padding, and border does not exceed the width value defined in the CSS file.

      Inspect one of the <div> elements with the browser developer tools to find how the box-sizing property has affected the box model. In the Firefox developer tools, width is defined as 128px, even though the width property in styles.css has a value of 250px. The computed value of the element is 250px, calculated by adding 128px plus 60px from the right padding, 60px from the left padding, 1px from the right border width, and 1px from the left border width. The Firefox developer tools box model is shown in the following image:

      Diagram of the box model set to border-box with margin set in yellow, border set in gray, padding set in purple, and the height and width set in blue.

      The box-sizing property can be changed on all elements of a web page by using the universal selector (*), also known as the star selector. This selector applies the styles to all elements on a page. This selector should be used with caution, since it does effect all elements and can potentially cause performance issues on pages that have a substantial amount of elements.

      Open styles.css and remove the box-sizing property from the div type selector. Then add a universal selector before the div selector with a box-sizing property set to border-box:

      styles.css

      * {
          box-sizing: border-box;
      }
      ...
      

      Save these changes to styles.css and reload index.html. You will find no difference visually. The responsibility of changing the box model has moved from an explicit setting to a universal setting.

      In this section, you used the box-sizing property to change how the box model behaves with the border-box value, creating a more comprehensive way of working with the box model. You also learned about the universal selector and how to apply the box-sizing property to all elements on a web page.

      Conclusion

      The box model is necessary to understand how styles are applied to elements and how styles affect the flow of content. In this tutorial, you learned how to use the border, padding, margin, height, and width properties and how they relate to each other in the box model. You used the default box model of the box-sizing property, which will help you plan and debug styling situations. Also, you learned about the border-box value that changes how the box model functions and allows for a more intuitive method of working with the box model. Remember that leaning into browser defaults helps maintain good performance, so changing the box model should be done as needed instead of universally.

      If you would like to read more CSS tutorials, try out the other tutorials in the How To Style HTML with CSS series.



      Source link

      How To Create a Featured Quote Box On Your Website Using CSS (Section 6)



      Part of the Series:
      How To Build a Website With CSS

      This tutorial is part of a series on creating and customizing this website with CSS, a stylesheet language used to control the presentation of websites. You may follow the entire series to recreate the demonstration website and gain familiarity with CSS or use the methods described here for other CSS website projects.

      Before proceeding, we recommend that you have some knowledge of HTML, the standard markup language used to display documents in a web browser. If you don’t have familiarity with HTML, you can follow the first ten tutorials of our series How To Build a Website With HTML before starting this series.

      Introduction

      In this tutorial, you will add a featured quote to your website using CSS as displayed in the sixth section of the demonstration website. You might use this section to feature a favorite quote, a testimony about your work, or a message to your site visitors. You can also hyperlink this quote to another webpage if you wish. The methods you use here can be applied to other CSS/HTML website projects.

      Featured quote section on demonstration website

      Prerequisites

      To follow this tutorial, make sure you have set up the necessary files and folders as instructed in a previous tutorial in this series How To Set Up You CSS and HTML Practice Project.

      To create the featured quote section, you will create a class to style the container and a class to style the featured text. In your styles.css file, add the following code snippets:

      styles.css

      . . .
      
      /* Section 6: Featured Quote  */
      
      .column-quote {
        width: 90%;
        height: 475px;
        padding: 40px;
        padding-left:70px;
        padding-right: 70px;
        padding-bottom:100px;
        margin:auto;
        margin-bottom:150px;
        border: 20px solid #FEDE00;
      }
      
      .quote {
        font-size:80px;
        font-weight:bold;
        line-height: 1;
        text-align: center;
      }
      

      In this code snippet, you have added the CSS comment /* Section 6: Featured Quote */ to label this section of the CSS code. Then, you have defined the class column-quote, which you will use to style the quote box, and specified the size, padding, margins, and border of the container.

      Note that the margin is set to auto, which horizontally centers the container in the middle of the page. In addition, the bottom margin is set to 200 pixels to give some space to the bottom of the page. If you want to learn more about the other declarations, please review the previous sections in this tutorial series on setting the sizes of content, padding, borders, and margins.

      You have also created the quote class, which you will use to style the text of the featured quote. Note that you have set the line-height property to 1, which shrinks the space between text lines from the default setting of 1.6. Experiment with changing this value to determine what line spacing you prefer.

      Save the styles.css file.

      Return to the index.html file. After the last closing </div> tag, add the following code snippet:

      index.html

      . . .
      
      <!--Section 6: Featured Quote-->
      
      <div class="section-break"> </div>
      <div class="column-quote">
        <p class="quote">There are many fish in the sea, but only one Sammy!</p>
      </div>
      

      Before moving on, let’s pause to examine each line of code:

      • The HTML comment <!--Section 6: Featured Quote--> labels this section of code in the index.html file and will not be displayed by the browser.
      • The <div class="section-break"> </div> element creates a section break using a class you may have defined in a previous tutorial. If you did not follow that tutorial, you can add that class by adding the CSS rule .section-break {margin:50px; height:500px;} to your styles.css file. This element creates space between the content in the previous section and the featured quote section.
      • The <div class="column-quote"> tag and its closing </div> tag create a container for the featured quote with the style rules you declared for the column-quote class in your styles.css file.
      • The <p class="quote">There are many fish in the sea, but only one Sammy! </p> inserts the text content into the <div> container you opened in the line above and styles it according to the rules you declared for the quote class selector in your styles.css file. If you change the length of your text content, you may want to modify one of the classes in this section to change the size of the font or the size of the container to make sure the text still fits.

      Save the index.html file and reload it in your browser. Your webpage should now display a large featured quote in a transparent container with a solid background:

      Featured quote section on demonstration website

      Conclusion

      In this tutorial, you created a featured text box on your website and modified its style for different website layouts. If you wish to hyperlink your quote to a new website page, please visit our tutorial How To Create and Link To Additional Website Pages With HTML.

      In the next and final tutorial of the tutorial series, you will create a static footer, which “sticks” in a fixed position at the bottom of the viewport as the visitor scrolls down the page.



      Source link