One place for hosting & domains

      Model

      Accessing the Document Object Model with JavaScript


      The Document Object Model (DOM) is a language-agnostic interface that provides access to an HTML document’s structure and content. JavaScript is often the language used to access the DOM in order to generate dynamic and interactive web pages.

      This guide provides an overview of the Document Object Model and shows you how to interact with it using a series of JavaScript examples.

      Before You Begin

      The examples in this guide use a web browser’s developer tools to view the DOM and interact with a JavaScript console. To get the most out of the information in this guide, follow along in your own Chrome or Firefox browser.

      • On Chrome, refer to Google’s
        Open Chrome DevTools
        documentation to learn how to access their developer tools.

      • On Firefox, refer to Mozilla’s
        Open the Inspector
        documentation to learn how to access their developer tools.

      What Is the Document Object Model?

      The Document Object Model (DOM) is an interface that provides access to an HTML document’s structure and content. The DOM represents the elements and content of an HTML document as nodes and objects. The DOM representation can then be accessed and modified by JavaScript and other scripting languages.

      Essentially, the DOM is what allows web pages to become dynamic. Languages like JavaScript work with the nodes that make up the DOM to dynamically and interactively change a web page’s presentation.

      There are many ways of displaying the DOM. One of the most widely used ways is the HTML format. When you open your browser’s Inspect dashboard, you can view the HTML representation of a web page. The example below shows the HTML markup for a simple web page.

      <!DOCTYPE html>
      <html>
        <head>
          <title>Example Page</title>
        </head>
        <body>
          <p>Example page content.</p>
        </body>
      </html>
      

      How the DOM Differs from HTML Source Code

      The DOM itself is not equivalent to a web page’s HTML source code. Instead, the DOM is a representation of how a web page is displayed in the moment that it is accessed.

      To illustrate how the DOM and HTML source code can differ, the example below displays an HTML source file. The HTML file includes a JavaScript function that adds additional HTML elements to the page once the page loads.

      File: example-page.html
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      
      <!DOCTYPE html>
      <html>
        <head>
          <title>Example Page</title>
          <script>
              function addExampleList() {
                  const exampleList = document.createElement("ul");
      
                  const exampleListItem1 = document.createElement("li");
                  const exampleListItem1Text = document.createTextNode("First item");
                  exampleListItem1.appendChild(exampleListItem1Text);
      
                  const exampleListItem2 = document.createElement("li");
                  const exampleListItem2Text = document.createTextNode("second item");
                  exampleListItem2.appendChild(exampleListItem2Text);
      
                  exampleList.appendChild(exampleListItem1);
                  exampleList.appendChild(exampleListItem2);
      
                  document.body.appendChild(exampleList);
              }
          </script>
        </head>
        <body onload="addExampleList();">
          <p>Example page content.</p>
        </body>
      </html>

      Once the HTML page is loaded and the JavaScript runs, the DOM representation of the HTML source above resembles the code displayed below. The JavaScript has been left out to make the resulting HTML easier to read. The HTML now includes an unordered list (<ul>...</ul>) with two list items (<li>...</li>).

      <!DOCTYPE html>
      <html>
          <head>
              <title>Example Page</title>
              <script>[...]</script>
          </head>
          <body onload="addExampleList();">
              <p>Example page content.</p>
              <ul>
                  <li>First item</li>
                  <li>Second item</li>
              </ul>
          </body>
      </html>
      

      Since the DOM is concerned with displaying the current state of an HTML page, it now displays the new HTML elements that were added to the page by the JavaScript. The DOM always reflects any additions, subtractions, or other modifications that happen to a web page. This characteristic is what enables the DOM to make web pages dynamic.

      The Document Object Model and JavaScript

      Most often, JavaScript is how web developers interact with the DOM. JavaScript is able to access the DOM with the document object and the nodes nested under it.

      The next sections explain what the document object is and the parts that make it up.

      Document Object

      To work with the DOM, client-side JavaScript provides the document object. This object includes properties and methods to access and modify the DOM.

      The previous section included some examples of the document object in action. Below are two additional commands that show more of the document object’s features.

      1. The document object’s properties provide information about the HTML document or access to its nested nodes. They also allow you to modify characteristics of the DOM as shown in the example below:

        document.body.style.backgroundColor = "blue";
        

        The example JavaScript accesses the document object’s backgroundColor property and sets its value to "blue". The web page it modifies should now have a blue background. The DOM representation of the change looks as follows:

        <!DOCTYPE html>
        <html>
            <head>
                <title>Example Page</title>
                <script>[...]</script>
            </head>
            <body onload="addExampleList();" style="background-color: blue;">
                <p>Example page content.</p>
                <ul>
                    <li>First item</li>
                    <li>second item</li>
                </ul>
            </body>
        </html>
        

        The color blue is assigned to the <body> element using the style attribute.

      2. The document object has several methods that do everything from provide access to specific nodes to add new nodes to the DOM. In the example below, the getElementsByTagName() method grabs every HTML element with the tag name, <li>. The JavaScript loops through those elements, and then outputs each elements textContent attributes.

        for (item of document.getElementsByTagName("li")) {
            console.log(item.textContent);
        }
        

        Using the for loop above, the JavaScript console should display the following output:

        First item
        Second item

      Nodes and Elements

      The document object contains numerous other objects that all make up the DOM. These objects are called nodes. Nodes include everything from HTML elements, to attributes, to text.

      You are likely to work most frequently with element nodes. DOM element nodes correspond to a web page’s HTML elements. They allow you to access and manipulate the building blocks of a web page.

      The script used in the
      How the DOM Differs from HTML Source
      section added a <ul> element and <li> elements to the page. This added the following two kinds of nodes to the page:

      • Element nodes, which were created using the document.createElement method.
      • Text nodes, created with the document.createTextNode method.

      Each part of the document object is actually a node of some kind or other. Additionally, each node inherits common properties, like the appendChild method, which lets elements add text nodes.

      The document object does more than just let you extend the DOM. For instance, you can also use it to navigate the DOM and make precise modifications to it. The script below demonstrates how these modifications can be made to the DOM. Access the
      example-page.html
      page in your browser. Then, open your browser’s JavaScript console, and enter in the following JavaScript:

      const listItems = document.getElementsByTagName("li");
      
      for (item of listItems) {
          const newTextNode = document.createTextNode(item.textContent.replace("item", "thing"));
      
          item.innerHTML = "";
          item.appendChild(newTextNode);
      }
      

      As a result, the DOM is updated and the text, item, contained within the <li> tags is updated to thing.

      <!DOCTYPE html>
      <html>
          <head>
              <title>Example Page</title>
              <script>[...]</script>
            </head>
            <body onload="addExampleList();">
              <p>Example page content.</p>
              <ul>
                  <li>First thing</li>
                  <li>Second thing</li>
              </ul>
          </body>
      </html>
      

      See our guide
      Traversing the Document Object Model with JavaScript
      , to learn about other built-in document object methods.

      Conclusion

      The DOM provides an interface to an HTML web page. This enables you to manipulate the structure and content of a web page using scripting languages, like JavaScript. This guide introduced you to the DOM and demonstrated how JavaScript is used to add, modify, and remove HTML elements from a web page.

      More Information

      You may wish to consult the following resources for additional information
      on this topic. While these are provided in the hope that they will be
      useful, please note that we cannot vouch for the accuracy or timeliness of
      externally hosted materials.



      Source link

      Traversing the Document Object Model with JavaScript


      The Document Object Model (DOM) is an interface that gives scripting languages, like JavaScript, access to a web page’s structure and content. You can learn more about the DOM and how it represents HTML in our guide
      Introduction to the DOM
      .

      The DOM is organized as a tree of objects, called nodes, that give access to everything from HTML elements to the text displayed on a web page. Understanding how to navigate and access nodes on this tree is essential to working with the DOM. This guide explains the DOM tree, how to navigate it, and how to access its nodes using JavaScript.

      Before You Begin

      The examples in this guide use a web browser’s developer tools to view the DOM and interact with a JavaScript console. To get the most out of the information in this guide, follow along in your own Chrome or Firefox browser.

      • On Chrome, refer to Google’s
        Open Chrome DevTools
        documentation to learn how to access their developer tools.
      • On Firefox, refer to Mozilla’s
        Open the Inspector
        documentation to learn how to access their developer tools.

      Most of this guide’s examples are based on an example web page created from the HTML source code displayed below. To follow along with this guide’s example,
      view the rendered example web page
      in your browser.

      File: example-page.html
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      
      <!DOCTYPE html>
      <html>
          <head>
              <title>Example Page</title>
          </head>
          <body>
              <div id="first-div" class="content-div">
                  <p>Example page content.</p>
                  <ul>
                      <li><span class="numeral-name" style="color: green;">First</span> item</li>
                      <li><span class="numeral-name" style="color: red;">Second</span> item</li>
                  </ul>
              </div>
              <div id="second-div" class="content-div">
                  <p><a href="https://loremipsum.io/">Lorem ipsum</a> dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Tortor condimentum lacinia quis vel eros donec. Purus ut faucibus pulvinar elementum integer enim neque volutpat ac. Netus et malesuada fames ac turpis egestas sed tempus. Nulla posuere sollicitudin aliquam ultrices sagittis orci a scelerisque. Et netus et malesuada fames ac turpis egestas sed. Purus ut faucibus pulvinar elementum integer enim neque. <em>Amet consectetur adipiscing elit ut aliquam.</em></p>
              </div>
          </body>
      </html>

      Understanding the DOM Tree

      The DOM is organized as a tree, each branch of which is a node. Though many nodes represent HTML elements, they also represent attributes and text associated with elements.

      In the following sections, you learn more about the structure of the DOM tree. You also learn about the components used to identify nodes and sets of nodes, which is the basis for effectively accessing nodes.

      What Is the DOM Tree?

      The
      document object
      is the base of all of the DOM’s nodes. The nodes are arranged as a tree, with nodes nested under other nodes. Below, is an example of the DOM representation of a simple web page:

      <body>
          <div>
              <p style="color: purple;">Paragraph text</p>
          </div>
          <div>
              <ul>
                  <li>First item</li>
                  <li>Second item</li>
              </ul>
          </div>
      </body>
      

      In the example above, elements nest under other elements. The two div elements are nested under the body element. Text nodes are nested under the p and li elements, and the style attribute is considered a node under the p element, as well.

      Plotting the nesting structure out, the DOM resembles the following tree:

      body
       \_ div
       |   \_ p
       |      \_ [text]
       |      |
       |      \_ [attribute]
       \_ div
           \_ ul
               \_ li
               |   \_ [text]
               |
               \_ li
                   \_ [text]
      

      Knowing the arrangement of the DOM tree and its leaves, helps you understand how to access specific nodes when working with JavaScript. This is especially true when you are working with more complicated web pages. The
      Navigating the DOM Tree
      section of this guide includes a more in-depth discussion on moving around the nodes of the DOM tree.

      The diagram below provides a visualization of the DOM tree for this guide’s
      example web page
      . You can also view the example-page.html file in the
      Before You Begin
      section of this guide.

      A DOM tree for an example web page

      How Are Nodes Accessed?

      When working with JavaScript, you need to pinpoint a node or a particular set of nodes to access. Nodes can be identified by the three components listed below:

      • Tags, used to define HTML elements. Common examples include div for page components, p for paragraphs, and a for hyperlinks.
      • Classes that distinguish between similar elements. Classes are optional, but let you apply CSS styles and let you differentiate between a subset of the same type of element.
      • IDs, which are meant to identify particular elements. These are most useful when applied to elements that you want to be able to conveniently and consistently select individually from the DOM.

      Although this is not always the case, the arrangement of these components above generally reflects the components’ specificity, from least specific to most. For instance:

      • A tag can be used to identify every div element on a page.
      • A class can identify a smaller set of those div elements.
      • An ID can identify a specific div element.

      The
      Navigating the DOM Tree
      section below shows how these components can be used to access particular elements or set of elements.

      Query Selectors

      The popular JavaScript library
      jQuery
      introduced query selectors. These give you advanced ways to access DOM elements, using the above three components as well as attributes and other node features. Query selectors even let you combine all of these in a single command.

      JavaScript now directly implements its own query selectors as well. This gives you access to advanced DOM selections, which are covered in depth later on in this guide.

      To give you an idea, the list below includes some examples of where you can use query selectors to fetch elements. The query selectors can be based on elements:

      • matching a specific sequence of tag, class, and/or ID
      • with a given attribute and/or attribute value
      • with a matching parent element
      • that do not match a query

      Once you understand the DOM’s tree structure and how its nodes are identified, you can start using JavaScript to access and alter the DOM. The sections below show how you can use JavaScript to select specific elements from the DOM. This is divided into two sections:

      1. Using standard methods on DOM objects. These have been around for a longer time and provide some of the most straightforward selection methods.
      2. Using query selectors. These are relatively new features in standard JavaScript and provide advanced selection methods. They are ideal when you want to make complicated queries in a few commands.

      How to Access Elements via Object Methods

      Most often, you can start accessing the DOM elements you need using methods from the document object. These allow you to match elements based on tag, class, or ID.

      Moreover, these methods are inherited by any element object. This makes it possible to navigate the DOM tree from element to element, narrowing it down to the specific elements you need.

      • To fetch elements based on tag, use the getElementsByTagName method:

         document.getElementsByTagName("p");
        
      • To fetch elements based on class, use the getElementsByClassName method:

         document.getElementsByClassName("content-div");
        
      • To fetch an element based on ID, use the getElementById method:

         document.getElementById("first-div");
        

      With the exception of getElementById, all the listed methods return an array of elements, no matter how many elements actually match the query. The getElementById method only returns the first matching element, even if multiple elements on the page have the same ID.

      The following example shows how you can traverse the DOM using a combination of the inherited document object methods. It also shows how you can leverage the fact that every element inherits these methods, allowing you to narrow your search down the DOM tree.

      // Fetch the element with the `first-div` ID. This uses the `document` object,
      // so the search looks at all elements on the page.
      const first_div_element = document.getElementById("first-div");
      
      // Fetch all of the `ul` elements from under the `first-div` element. Remember,
      // this method returns an array, even if there is only one matching element.
      const ul_elements = first_div_element.getElementsByTagName("ul");
      
      // Fetch the elements with the `numeral-name` class from under the first
      // element in the array of `ul` elements.
      const numeral_elements = ul_elements[0].getElementsByClassName("numeral-name");
      
      // Grab and print the `style.color` value from each of the matching
      // `numeral-name` elements.
      for (const span_element of numeral_elements) {
          console.log(span_element.style.color);
      }
      

      If you run the above JavaScript in your web browser’s developer tools console, you see the following output.

      green
      red

      From the example above, you could also get to the numeral-name elements directly using the following code:

      const numeral_elements = document.getElementsByClassName("numeral-name");
      

      The approach of using particular elements’ methods to select lower elements on the tree can be extraordinarily helpful in some cases. For instance, if you want to select only the p elements from the second div, use the following JavaScript code:

      const second_div_element = document.getElementById("second-div");
      const p_elements = second_div_element.getElementsByTagName("p");
      

      How to Access Elements via Query Selectors

      Query selectors give you more advanced options for selecting elements from the DOM. They can be accessed via two methods from the document object — and they are also inherited on all other element objects. The two methods are the following:

      • querySelector fetches one element matching the query string. If multiple elements match, the method only returns the first one.
      • querySelectorAll fetches an array of elements matching the query string. Even if only one element matches, the result is an array.

      Like the methods covered in the previous section, these query selector methods let you select elements based on tag, class, and ID. However, the query selector syntax also lets you combine element selectors, and expands on how you can search for specific elements.

      The following examples display some key ways in which you can use query selectors to navigate and access elements from the DOM.

      • You can look for elements with a specific combination of tag, class, and ID. For instance, to search for a combination of the div tag, the content-div class, and the first-div ID, use the following code:

          document.querySelectorAll("div.content-div#first-div");
        

        The query selector syntax uses . to precede class names and # to precede IDs. It assumes labels without a prefix to be tag names.

      • You can look for elements nested under particular elements. These are called the descendants of an element. The following example finds em elements nested somewhere under any element with the content-div class:

          document.querySelectorAll(".content-div em");
        
      • You can look for elements based on associated attributes. The example below accesses the first element with an href attribute:

          document.querySelector("[href]");
        

        Alongside this, you can also specify the tag, class, and/or ID. This allows you to narrow down the search to elements whose attribute has a specific value:

          document.querySelector("a[href="https://loremipsum.io/"]");
        
      • You can look for elements based on their direct parent elements. The next command fetches all p elements that are immediate children of any div elements with the first-div ID:

          document.querySelectorAll("div#first-div > p");
        

        This selector is more specific than the descendant selector above. Where the descendant selector div em grabs an element from the example page, the child selector div > em does not.

        Why is this? The page’s em element is a direct child of a p element — that is, nested immediately under a p element — but not a div element. It is only a descendant of a div element, meaning it is nested somewhere, however deeply, beneath one.

      • You can look for elements that do not have a certain matching quality. For instance, the example below gets all p elements that are not a child of an element with the first-div ID:

          document.querySelectorAll("p:not(#first-div > p)")
        

      The above is, in fact, just a selection of some of the most commonly used features of the query selector. You can get more examples of query selector options in the
      More Information
      section of this guide.

      Conclusion

      This tutorial walked you through what the DOM tree looks like, how to navigate its parts, and how to start accessing them. The
      links below
      give you some resources to learn more about navigating the DOM, with more examples and coverage of advanced options and scenarios.

      More Information

      You may wish to consult the following resources for additional information
      on this topic. While these are provided in the hope that they will be
      useful, please note that we cannot vouch for the accuracy or timeliness of
      externally hosted materials.



      Source link

      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