One place for hosting & domains

      How To Style a Table with CSS


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

      Introduction

      Tables have a long and complicated history on the web. Before CSS existed, the <table> element was the only possible avenue for creating rich design layouts on the Web. But creating layout with <table> was not its intended or ideal use. Now that better layout options are available, developers can use the <table> element for presenting tabular data as intended, much like a spreadsheet. This allows for semantic HTML, or using HTML elements in alignment with their intended meaning.

      Well-formatted HTML provides information to a browser and allows the browser to provide the best interface for the user. While this tutorial will focus on the visual aspect of styling a table, effective table HTML ensures that all users, including sighted, non-sighted, and users with other circumstances, will be able to navigate and comprehend the tabular information. Using the <table> element as intended can greatly increase the accessibility of your CSS design.

      In this tutorial, you will run through an example of styling a <table> element. The first half of this tutorial will focus on a common table layout that mostly uses the browser’s default styles for table elements. Browser defaults are the starting point of working with CSS, so it is important to know what they are. The second half will refactor the table to use unique styles for each section. By the end of the tutorial you will have built a table that has distinct styles for x-axis and y-axis table headings, alternating row colors, a clear caption for the table, and a highlighted data point, as shown in the following image:

      Table of financial information with custom style that renders a sans-serif font, a black header row, blue row headers, and different shading values for each row.

      Prerequisites

      Setting Up the <table> HTML

      Before you can style a <table>, you need one to work with. There are a lot of possible elements that can exist within a <table> element. The <table> element is one of the best examples of HTML semantics, as it only works when it has table-related descendent elements within it. In this step, you will create a <table> element and populate it with example data.

      To start, open index.html in your text editor and add the HTML in the following code block:

      index.html

      <!doctype>
      <html>
        <head>
          <title>2019 Fourth Quarter Report</title>
          <link href="https://www.digitalocean.com/community/tutorials/styles.css" rel="stylesheet" media="all" />
        </head>
        <body>
          <table>
          </table>
        </body>
      </html>
      

      All the HTML you will add from this point forward will go inside the <table> element. The <table> element itself only defines the tabular content area, and must have specific elements inside of it to work properly. The <link> element references the styles.css file that you’ll add later and will load the CSS onto the page to generate the styles. The media attribute designates what device the content is made for. In this case, you’ve set it to all, since this is for all device types.

      First, you’ll add the <caption> element within the <table> element, with the text of 2019 Fourth Quarter Report inside. In the index.html file in your text editor, add the highlighted HTML from the following code block:

      index.html

      ...
      <table>
        <caption>2019 Fourth Quarter Report</caption>
      </table>
      ...
      

      The <caption> contains the name or description of the table. Be sure to include this element in your tables, as it provides useful information for those who use assistive technologies, such as a screen reader. It may be helpful to think of a <caption> element as the <title> of the <table>.

      Next, add the <thead> followed by the <tbody> elements as siblings to the <caption> element, as shown in the highlighted HTML in the next code block:

      index.html

      ...
      <table>
        <caption>2019 Fourth Quarter Report</caption>
        <thead></thead>
        <tbody></tbody>
      </table>
      

      The <thead> element is the <table> equivalent of <header> and defines a context for heading information. Like the <thead>, the <tbody> element defines the area where the tabular content will reside. In both cases they define an area, but on their own they do not show content. While not used in this example, the <tfoot> element exists to provide summary information, such as totals.

      A table in HTML is built by rows, not columns. Each cell of the table is contained within a <tr> element. These elements are usually descendants of <thead>, <tbody>, and <tfoot>, but can also be a direct descendant of <table> if the area elements are not used.

      Return to the index.html in your text editor to add a single heading row and three rows of content in the body, as highlighted in the following code block:

      index.html

      ...
      <table>
        <caption>2019 Fourth Quarter Report</caption>
        <thead>
          <tr></tr>
        </thead>
        <tbody>
          <tr></tr>
          <tr></tr>
          <tr></tr>
        </tbody>
      </table>
      ...
      

      The last two elements are functionally similar and are both the final element in the <table> HTML structure, meaning unlike the previous elements, these can contain non-table elements.

      <td> elements contain the individual table data points. <th> defines content as a heading for a row or a column. Table elements are unique to HTML as their markup structure correlates directly with a visual structure. When considering a table as a spreadsheet, the <th> and <td> elements behave as the cells. In order to have four columns in this table, each <tr> will need to have no more and no less than four <td> or <th> elements. Depending on the content of the data, this may mean there is a blank <th> or <td> element. It can be helpful to use an HTML comment to explain when an element is intentionally left blank.

      Add the highlighted HTML from the following code block to your index.html file:

      index.html

      ...
      <table>
        <caption>2019 Fourth Quarter Report</caption>
        <thead>
          <tr>
            <th><!-- Intentionally Blank --></th>
            <th>October</th>
            <th>November</th>
            <th>December</th>
          <tr>
        </thead>
        <tbody>
          <tr>
            <th>Projected</th>
            <td>$820,180</td>
            <td>$841,640</td>
            <td>$732,270</td>
          </tr>
          <tr>
            <th>Actual</th>
            <td>$850,730</td>
            <td>$892,580</td>
            <td>$801,240</td>
          </tr>
          <tr>
            <th>Utilization</th>
            <td>83%</td>
            <td>90%</td>
            <td>75%</td>
          </tr>
        </tbody>
      </table>
      ...
      

      Note: Like in spreadsheet software, there are times that it may be necessary to merge cells, such as when a single cell takes up two columns. This is possible to do, but only with the use of HTML attributes on the cells, and not with CSS. It is important to keep this in mind when dealing with more complex tables.

      Now that you have written out your table, save the file. Then, open index.html in your web browser. The following image depicts how the browser default styles for this table will look when loaded in the Firefox web browser:

      Information arranged into a table, but with no dividing lines and with default serif font.

      In this section, you set up the HTML for the tabular data. You learned about how a table is made of a series of elements combined in a distinct order to create an accessible dataset. Next, you will use the border and border-collapse properties to begin applying styles to the table.

      Using border and border-collapse to Create the Initial Table Style

      The first step to styling a table is understanding some of the browser default styles and behaviors. This section will cover the border property and the border-collapse property, and show how to create a boundary line between cells.

      To begin styling your table, create and open a file named styles.css in your text editor, in the same folder as index.html. Add a selector group consisting of a th element selector and a td element selector. Then, in the selector block, add a border property with a value of 1px solid black, as shown in the following code block:

      styles.css

      th, td {
        border: 1px solid black;
      }
      

      Save your changes to styles.css and then open index.html in your web browser. Instead of a cohesive grid, there will be several boxes with their own borders. The following image depicts how the table will appear in a web browser:

      Default borders separated table with borders style of 1px black solid.

      To change this default, return to styles.css in your text editor and add a table element selector to the top of the file. Then, in the selector block, apply the border-collapse property. This property defaults to separate, but here you will change it to a value of collapse. This removes the spacing between the table cells and causes the borders to overlap. The highlighted CSS in the following code block indicates what to add to your styles.css file:

      styles.css

      table {
        border-collapse: collapse;
      }
      
      th, td {
        border: 1px solid black;
      }
      

      Open your web browser and refresh index.html. The table will now have a grid defined by multiple crossing black lines. The following image depicts how the borders will appear in your browser:

      Table with no space between cells and a border style of 1px black solid.

      In this section you used the border property to apply a border on each table cell with the th and td element selectors. You also learned that by default table cells are separated by a space. You used the border-collapse property applied to the table element selector with the collapse property to remove the space between table cells. In the next section, you will use the padding and width properties to define the size of the table.

      Setting the Size of the Table

      Next, you will add some spacing to the table cells to make the data more readable. To address adding in white space to the table cells and making the table more balanced, this section will focus on the width and padding properties.

      As of now, the content of each cell is bunched up, with the borders right on top of the content. You may have also noticed that the table is only as wide as its content. <table> has its own display property: display: table. To make the table go the full width of the parent container, a width: 100% can be added to the table selector.

      As this is a relatively small table, adding a width property to the <table> element isn’t necessary. Instead, open styles.css in your text editor and add a combinator selector consisting of thead th, which will scope styles to <th> elements inside of a <thead> element. Then, add a width property with a value of 25%, as indicted in the highlighted portion of the following code block:

      styles.css

      ...
      th, td {
        border: 1px solid black;
      }
      
      thead th {
        width: 25%;
      }
      

      Since there are four columns in this table, you can give each column an equal width by applying a width: 25%. Only the first cell of each column needs to be set, hence the thead th selector. The width of one cell determines the width of all cells in that column.

      After saving your changes to styles.css, return to your browser and refresh index.html. The table will now have four columns of the same width, as depicted in the following image:

      Set equal column widths

      Note: If you wish to have varying widths for each column, apply a specific class to each th in the column. Then, using those classes, set your desired width.

      Now that the columns are equal widths, the content of each cell could use some more space inside by using the padding property. Unlike the width property, applying space inside the cell requires targeting all the th and td cell elements.

      Open styles.css in your text editor and add a padding property to the group selector for th, td, then give it a value of 8px. The highlighted line in the following code block indicates the necessary change:

      styles.css

      ...
      th, td {
          border: 1px solid black;
          padding: 8px;
      }
      
      thead th {
        width: 25%;
      }
      

      Save your changes to styles.css, then refresh index.html in the browser. The 8px padding is added to each side of each cell, providing space to make the tabular data more legible. The following image depicts how this will appear in the browser:

      Adding space within cells.

      Note: The box model for table cells is an outlier from the usual model, and does not recognize the margin property.

      In this section, you set the width property of each column to be equal and you added spacing to each cell using the padding property to make the data easier to read. In the next section, you will use a class to target and style a specific table cell.

      Targeting a Specific Table Cell

      In this step, the goal is to visually highlight one of the cells in the table. You will apply a class name in the HTML, then use a class selector and background-color property to create the highlight effect.

      To begin, open index.html in your text editor and add a class attribute to the <td> element with the text 90% inside. Give the class attribute a value of cell-highlight, as indicated in the highlighted HTML of the following code block:

      index.html

      <table>
        ...
        <tr>
          <th>Utilization</th>
          <td>83%</td>
          <td class="cell-highlight">90%</td>
          <td>75%</td>
        </tr>
        ...
      </table>
      

      Save your changes to index.html, then open styles.css in your text editor. Append to the end of the file a class selector of .cell-hightlight. Inside the selector block, add a background-color property with a value of gold. Next, add a font-weight property with the value set to bold. The highlighted CSS in the following code block demonstrates how this is formatted:

      styles.css

      ...
      thead th {
        width: 25%;
      }
      
      .cell-highlight {
        background-color: gold;
        font-weight: bold;
      }
      

      Save your changes to styles.css, then return to the web browser and refresh index.html. As the following image showcases, the table cell with the content of 90% now has a deep yellow background and a bold font weight:

      A table with gold highlighting on a specific cell.

      You’ve now used a class selector on a specific table cell to apply a highlight style using the background-color and font-weight properties. Next, you will change the border placement, font, and text alignment to move the styles toward the final look of the table.

      Setting the Font Family for the Table

      To begin moving toward the final style of the table, you will move the border to be around the whole table, instead of the individual cells. Then, you will set a new default font-family for the page and adjust the default text alignment for the individual cells.

      To update the borders, open styles.css in your text editor. Then, edit the existing group selector th, tr by removing the border: 1px solid black; property and value. This will remove the cell borders from the table; the padding will remain the same for the second stage of the table styles. Then, on the table type selector, add a border property with a value of 1px solid black. The following code block demonstrates how this will appear in your code:

      styles.css

      table {
        border-collapse: collapse;
        border: 1px solid black;
      }
      
      th, td {
        padding: 8px;
      }
      ...
      

      Save your changes to styles.css and return to your browser to refresh index.html. The border will now surround the whole table instead of the individual table cells, as illustrated in the following image:

      Table with a black border around the whole table but with no borders between the individual cells.

      To change the font for the whole document, return to styles.css in your text editor. Before the table selector block, add a body type selector. Within the body selector block, add the font-family property with a value of sans-serif. This will set the font for the page to the browser’s default sans-serif font, such as Helvetica or Arial. The highlighted CSS in the following code block indicates the changes to styles.css:

      styles.css

      body {
        font-family: sans-serif;
      }
      
      table {
        border-collapse: collapse;
        border: 1px solid black;
      }
      ...
      

      Save these changes to styles.css, then reload index.html in the browser. The font for the whole table will now have the browser’s default sans-serif font, as shown in the following image:

      Table with all the default serif font changed to the default sans-serif font.

      Finally, to adjust the alignment of the table’s contents, return to styles.css in your text editor. Browsers typically default the content alignment to a top left position. Similar to aligning content in a spreadsheet application, tables can have the content aligned to the middle of a table cell regardless of row height.

      To set the horizontal middle alignment, go to the table type selector and add the text-align property with a value of center. Then, to set the vertical middle alignment, add the vertical-align property with a value of middle. The highlighted section of the following code block demonstrates how to add this to styles.css:

      styles.css

      body {
        font-family: sans-serif;
      }
      
      table {
          border-collapse: collapse;
          border: 1px solid black;
          text-align: center;
          vertical-align: middle;
      }
      ...
      

      Save your changes to styles.css and then return to the web browser to reload index.html. The cell contents will now be horizontally and vertically centered within the cell. Note that the <th> cells have not changed their spacing. This is because table headers have centered text as a default.

      The vertical centering will not be immediately evident with the content as it is, but should the content of one cell wrap to a second line, the remaining cells in the row will vertically align their contents.

      The following image shows how this will appear in the browser:

      Table with the contents of each cell horizontally and vertically centered within the cell.

      In this section, you moved the border property from the table cells to the whole table. You also set a new font family for the page and changed the default alignment for the contents of the table cells. In the next section, you will add styles to the table’s <caption> element and learn more about its purpose.

      Styling the Table Caption

      The <caption> element provides context for both sighted and non-sighted readers of the table and displays above the table, regardless of where the <caption> is within the <table> element. For screen reader and braille users, a <caption> provides clear context of the purpose of a table, especially when there are multiple tables on a page.

      Since <caption> is an element that only occurs inside of a <table> element, it can be styled with the caption type selector. The default for caption is centered text, with an inherited size, family, and a regular weight.

      To begin changing the styles of the <caption> element, open styles.css in your text editor. Add a caption selector after the table selector in order to keep your CSS in a logical flow order. Then, using the font-weight, font-size, text-align, and color properties, create a caption that is large, bold, left-aligned, and dark gray. The highlighted CSS in the following code block demonstrates how this will be formatted:

      styles.css

      table {
        border-collapse: collapse;
      }
      
      caption {
        font-weight: bold;
        font-size: 24px;
        text-align: left;
        color: #333;
      }
      
      
      th, td {
        border: 1px solid black;
        padding: 8px;
      }
      ...
      

      Save your changes to styles.css and reload index.html in your browser. As shown in the following image, the caption contents are now much larger and bold, creating a heading for the table:

      Table with caption left-aligned and bolded as the title.

      Next, some space is needed between the caption and the visual part of the table. Return to styles.css in your text editor to add additional spacing to the caption.

      The caption can accept margin and padding spacing properties. Since the spacing is only needed beneath the caption, add a margin-bottom property to the selector block with a value of 16px. The highlighted line of the following code block indicates how to apply this:

      styles.css

      caption {
          font-weight: bold;
          font-size: 24px;
          text-align: left;
          color: #333;
          margin-bottom: 16px;
      }
      

      Save your changes to styles.css and refresh index.html in the web browser. The caption now has more space between the text and the table, as shown in the following image:

      Table with space between the caption and the table itself.

      In this section, you created custom styles for the table’s <caption> element. You also learned that the <caption> is an important element to provide informational context to those using assistive technologies to read the table. In the next section, you will apply styles to the top heading table row.

      Next, you will apply styles to the top row headings. The <thead> element will contain the top row, so all styles for this can be applied to that element directly. The intent will be to create a dark gray background with white, all uppercase text.

      To start, open styles.css in your text editor. Create a new thead type selector. In the selector block, add a background-color property with a value of #333, which will create the dark gray color. Then, add a color property with a value of white:

      styles.css

      ...
      caption {
        font-weight: bold;
        font-size: 24px;
        text-align: left;
        color: #333;
        margin-bottom: 16px;
      }
      
      thead {
        background-color: #333;
        color: white;
      }
      ...
      

      Save you changes to styles.css and refresh index.html in your browser. The top heading row is now visually distinctive, with a solid black background and bold white text. The following image shows how this will appear in the browser:

      Table with the table header row in dark gray with white lettering.

      Next, to add a bit more to the aesthetic of the top header, return to styles.css in the text editor. Change the size of the text by adding a font-size property with a value of 0.875rem, which will bring the font-size down a little. Then, to make all the letters capitals, add a text-transform property with uppercase as the value. Finally, to give some space between the letters, use the letter-spacing property and set the value to 2%. This will create a sufficient space between the uppercase characters so they aren’t bunched up, making them easier to read.

      The highlighted CSS in the following code block demonstrates how to format these styles:

      styles.css

      thead {
          background-color: #333;
          color: white;
          font-size: 0.875rem;
          text-transform: uppercase;
          letter-spacing: 2%;
      }
      

      Save your changes to styles.css and then return to your browser to refresh index.html. As shown in the following image, the text is now uppercase, a bit smaller in size than the cell contents, but hierarchically clear as a heading:

      Table with header row lettering changed to uppercase and adjusted for spacing.

      In this step, you used several properties to provide a discernible style to the top heading row. The HTML for this portion of the table was already accessible for non-sighted and assertive technology users. Now, the visual styles provide more contextual information. Next, you will continue to work with visual aids by adding alternating row colors.

      Adding Striped Row Styles to the Table

      Next, to create the alternating stripe colors, you will need to use what is called a pseudo-class selector. There are various kinds of pseudo-classes, and in this case you will use the :nth-child() pseudo-class. The parentheses after :nth-child can take various numbers and word values to create an alternating style that will include the odd and even values.

      To begin, open styles.css in your text editor. The :nth-child() pseudo-class works by applying it to sibling elements. In this case, that will be <tr> elements inside of <tbody>. To create the first value, write a tbody tr combinator selector, immediately followed by the :nth-child(odd) pseudo-class. In this selector block, set the background-color property to #fff, the hexadecimal shorthand for white. Then create another selector in the same format, but use even instead of odd and set that background-color property to the light gray #eee value.

      The highlighted CSS in the following code block showcases how this will appear in your text editor:

      styles.css

      ...
      .cell-highlight {
        background-color: gold;
        font-weight: bold;
      }
      
      tbody tr:nth-child(odd) {
        background-color: #fff;
      }
      
      tbody tr:nth-child(even) {
        background-color: #eee;
      }
      

      Save your changes to styles.css then return to index.html in your browser and refresh the page. The second row will now have a light gray background, and though it won’t look different, the odd rows now have a defined white background instead of its default transparent. As you add rows, these styles will alternate from white to light gray. The following image demonstrates how this will appear in the browser:

      Table with alternating rows of white and gray background colors.

      In this section, you used the :nth-child() pseudo-class to create alternating row colors in the body section of the table. In the last section of this tutorial, you will pair together what you learned in the previous two sections to create custom styles for the row headings on the left side of the table.

      The last styling for this table is to add a blue background to the y-axis headers on the left side of the table. This will occur in two parts: the first will be similar to the section styling the top heading row by targeting the th cells in each row. Then you will create a color shift using the same :nth-child() pseudo-class approach from the previous section.

      To apply the primary blue background, open your styles.css file in a text editor. You need to target the <th> elements in the <tbody> so that the <th> elements in the <thead> don’t get these styles. Create a combinator selector of tbody th, then give it a background-color property and value of #36c. Apply a color property with a value of #fff or white. Finally, to set the text to be left-aligned, add a text-align property set to the value of left:

      styles.css

      ...
      tbody tr:nth-child(even) {
        background-color: #eee;
      }
      
      tbody th {
        background-color: #36c;
        color: #fff;
        text-align: left;
      }
      

      Save your change to styles.css, then refresh index.html in your browser. As shown in the following image, the row headings are now a distinctive blue color with white text:

      Table with left-most column in blue with white lettering.

      Lastly, to carry over the alternating row colors into the row header, return to styles.css in your text editor. To accomplish the same effect as the data row, you will need an :nth-child() pseudo-class selector. Since a blue background is already set on the tbody th combinator selector, you only need :nth-child(even) to adjust to a darker blue. However, due to how the :nth-child() pseudo-class selector works, you will still need to apply it to the <tr> element and not the <th> element, since the row (tr) counting is how the effect is achieved. This will require a more complex combinator selector of tbody tr:nth-child(even) th with a background-color property set to #25c.

      The following code block highlights how this CSS is formatted:

      styles.css

      ...
      tbody th {
        background-color: #36c;
        color: #fff;
        text-align: left;
      }
      
      tbody tr:nth-child(even) th {
        background-color: #25c;
      }
      

      Save your changes to styles.css then return to your browser one last time and refresh index.html. The styling is now complete with alternating row colors across the row headers and the data, as depicted in the following image:

      Table with alternating shades of blue in the left-most column to match the rest of the table.

      In this section, you scoped styles to row headings and carried over what had been learned in previous sections to accurately target an alternating background color.

      Conclusion

      You’ve now successfully built a table and learned several practical CSS properties and selector types to apply to tabular data. Going forward, you can make more complex tables that take these concepts further. You can also use the nth-child selector to create alternating styles on bullet lists or navigation links. HTML tables are highly useful to present various kinds of tabular data, and the capabilities of HTML and CSS allow for a vast array of table types.

      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 Select HTML Elements Using ID, Class, and Attribute Selectors in CSS


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

      Introduction

      Writing CSS selectors most often involves setting a condition and locating the element in the HTML that fulfills that condition as true. You can do this broadly with an element selector to select high-level tags, but to gain more control over the selected elements, you can create specific identifiers in the HTML and apply them in the CSS.

      In this tutorial, you will use the id, class, and attribute selectors to scope styles to intentionally written HTML. You will begin by creating an HTML and a CSS file that you will edit throughout the tutorial. You will then add id attributes and use those id values to target styles. You will also add class attributes to elements and use those class values independently and together to create more specific and reusable styles. Lastly, you will use the attribute selector to create styles that match much more specific scenarios than an id or class selector alone can accomplish.

      Prerequisites

      Setting Up the Base HTML and CSS

      To start working with id, class, and attribute selectors, you will first set up the HTML and CSS code that you will work on through the rest of the tutorial. In this section, you will write out all the necessary HTML and some initial CSS styles that will handle layout and start the visual aesthetic.

      To begin, open index.html in your text editor. Then, add the following HTML to the file:

      index.html

      <!doctype html>
      <html>
        <head>
        </head>
        <body>
        </body>
      </html>
      

      Next, go to the <head> tag and add a <meta> tag to define the character set for the HTML file. Then add a <meta> tag defining how mobile devices should render the page, set the title of the page, and finally load the CSS file that you will make later with a <link> tag.

      These additions are highlighted in the following code block. You will encounter this highlighting method throughout the tutorial as code is added and changed:

      index.html

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

      After adding the <head> content, move to the <body> element where you will add content for a page talking about CSS selectors. Add the highlighted section from this code block to your index.html file in your text editor:

      index.html

      <!doctype html>
      <html>
        <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <title>Link and Buttons with State</title>
          <link rel="stylesheet" href="https://www.digitalocean.com/community/tutorials/styles.css">
        </head>
        <body>
          <header>
            <h1>Using CSS Selectors</h1>
          </header>
      
          <main>
            <section>
              <h2>Selecting HTML To Style</h2>
              <p>Selecting the right element and providing the right visual styles is the basis of <a href="https://do.co/community">writing CSS</a> code. Whenever you need to adjust how an element on a webpage looks, using selectors is key.</p>
              <p><a href="https://example.com">Read this to learn more about selectors</a></p>
            </section>
      
            <section>
              <h2>The Type Selector</h2>
              <p>The type selector finds elements on the page by tag name. This is a common way to style elements on the page. Type selectors are often referred to as element selectors.</p>
            </section>
      
            <section>
              <h2>Combining Selectors</h2>
              <p>A combinator selector is defined by a space character between selectors, with the HTML ancestry reading left to right. The right-most selector is the intended target. This can be as complex or as simple as necessary to <em>scope</em>, or provide sufficient specificity, to the intended element.</p>
            </section>
          </main>
        </body>
      </html>
      

      Save your changes to index.html and leave it open in your text editor. Open up your browser and load index.html to render the content of the page with the browser default styles. The following image shows these default styles with black serif text on a white background:

      Black serif text in various sizes with two blue, underlined links.

      Next, return to your text editor and create a file called styles.css. This is the file that you referenced in the <head> element in your index.html. In the styles.css file, add the following code:

      styles.css

      body {
        font-family: sans-serif;
        line-height: 1.5;
        color: #444;
      }
      

      This CSS uses a body type selector to set the default font-family for the page to the browser’s sans-serif font. Then it changes the spacing between lines of text to 1.5 times the font-size. Lastly, the color value changes the text to a dark grey, instead of the default black.

      Save these changes to styles.css and return to the browser to see how these changes will appear, as shown in the following image:

      Dark gray sans-serif text in various sizes with two blue links with underlines.

      You have now set up the starting points for your index.html and your styles.css. In the next section, you will add an id attribute to elements in the HTML and create id selectors in the CSS to apply styles to those elements.

      Using the ID Selector

      In this section, you will learn about the id attribute and its purpose, then add several id attributes to your HTML. Finally, you will use some of these id selectors to apply layout styles.

      The id attribute is a unique identifier that links together content on the page. For example, say there is an element midway down the content of a web page with an id attribute of my-id. By appending that id value with a pound or hash symbol (#) to the URL, such as http://example.com/index.html#my-id, the browser will scroll to that section of the page. Since this can be used as part of the URL and for other scripting purposes, each id value on a page must be unique.

      To begin working with the id attribute, open index.html in your text editor. First, locate the <header> element and give it an id attribute with the value of header. Next, move to the <main> element and give it an id attribute with a value of content. These id attributes provide a unique identifier for the two primary sections of the content. The highlighted additions in the following code block show the changes you will make to your index.html file:

      index.html

      ...
      <header id="header">
        ...
      </header>
      <main id="content">
        ...
      </main>
      ...
      

      Note that well-written HTML will only have one <header> element and one <main> element, so it may seem redundant to assign a unique ID to elements that are already unique. However, applying specific IDs like this can separate your styling from your HTML structure, allowing you to retain consistent styling attached to the IDs even if the underlying HTML changes.

      Be sure to save your changes to index.html before continuing.

      The id selector in CSS uses the same format as when referenced in a URL: a pound sign followed by the name of the id, such as #my-id. To begin using the id selector, open styles.css in your text editor. Then, add the two id attribute values from your index.html as the group combinator #header, #content. You will use this selector to set the content of the <header> and the <main> element uniformly in the middle of the page. The following code block has the selector block and the code necessary for this layout:

      styles.css

      body {
        font-family: sans-serif;
        line-height: 1.5;
        color: #444;
      }
      
      #header,
      #content {
        margin: 1em auto;
        width: 90%;
        max-width: 60ch;
      }
      

      The id selectors will apply a margin of 1em to the top and bottom of both the <header> and the <main> element. The auto value on the margin property keeps the content centered to the page when paired with the width property of 90%. Lastly, the max-width property stops both containers from growing any wider once they reach a size of 60ch, which is equivalent to 60 0 characters in width.

      Save your changes to styles.css then open index.html in your browser. The contents of the page are now centered to the page instead of stretching across the length of the window. The following image illustrates how this appears in the browser:

      Text content centered to roughly half the width of the full size.

      In this section, you learned about the id attribute and used this attribute to apply styles to elements. You also learned that the id attribute is required to have a unique value because of how it can be used by the browser in URLs and in scripting. Next, you will use the class attribute to refactor the code from this section to apply colors to the content with new classes.

      Using the Class Selector

      In this section, you will use the class selector to find specific element on a page using values found in the class HTML attribute. You will refactor the id selectors to use a reusable class instead. The class attribute is meant to create a specific targetable value that styles can be applied to. Unlike the id, the values of class attributes can be reused, which is its advantage over the id selector.

      To begin styling elements with class, start by opening the index.html file in your text editor. On both the <header> and <main> elements, add a class attribute with a value of content-width. The highlighted section of the following code block indicates how to add the class attribute:

      index.html

      ...
      <header id="header" class="content-width">
        ...
      </header>
      <main id="content" class="content-width">
        ...
      </main>
      ...
      

      Save the changes to index.html, then open styles.css in your text editor to create the class selector for this class value.

      The class selector is similar to id in that it has a special character in CSS, which is indicated by the period symbol (.). In the styles.css file, locate the selector with the IDs #header, #content and replace both selectors with the .content-width class selector. The following highlighted code indicates the change you will make in your code:

      styles.css

      body {
        font-family: sans-serif;
        line-height: 1.5;
        color: #444;
      }
      
      .content-width {
        margin: 1em auto;
        width: 90%;
        max-width: 60ch;
      }
      

      Save these change to your styles.css and return to your browser. Refresh index.html and the styles will remain unchanged. The refactor to the code didn’t change the styles, but did change how the elements are selected. The versatility of a class is that the styles can be used more than once and on different element types.

      Next, return to index.html in your text editor and add a class attribute to the <h1> element with a value of style-1. This defines a class name that will be used in your CSS. The following code block indicates this change in the highlighted section:

      index.html

      ...
      <header id="header" class="content-width">
        <h1 class="style-1">Using CSS Selectors</h1>
      </header>
      ...
      

      Next, on each of the <h2> elements within the <main> element, add a class attribute. Give all three of these class attributes the value of style-2. Use the highlighted sections of the following code block for reference:

      index.html

      ...
      <main id="content" class="content-width">
        <section> 
          <h2 class="style-2">Selecting HTML To Style</h2>
          ...
        </section>
      
        <section>
          <h2 class="style-2">The Type Selector</h2>
          ...
        </section>
      
        <section>
          <h2 class="style-2">Combining Selectors</h2>
          ...
        </section>
      </main>
      ...
      

      After adding the class attributes to the elements in the index.html file, be sure to save the changes. Then, open styles.css in your text editor and create a class selector for the style-1 class.

      Add to the end of the styles.css a selector called .style-1. The period tells the browser to look for a class attribute on the page with the name of style-1. Then create a selector block and add a font-size property with a value of 1.25rem, a text-transform property set to uppercase, and a letter-spacing property to put 0.125em space between the characters. The following code block indicates these additions in the highlighted sections:

      styles.css

      ...
      .content-width {
        margin: 1em auto;
        width: 90%;
        max-width: 60ch;
      }
      .style-1 {
        font-size: 1.25rem;
        text-transform: uppercase;
        letter-spacing: 0.125em;
      }
      

      Next, create another class selector, this time for the style-2 class. Be sure to add the period before the name of the class value. Then add to that selector a font-size property with a 2rem value and a font-weight property set to normal. Reference the highlighted code in the following code block:

      styles.css

      ...
      .style-1 {
        font-size: 1.25rem;
        text-transform: uppercase;
        letter-spacing: 0.125em;
      }
      
      .style-2 {
        font-size: 2rem;
        font-weight: normal;
      }
      

      Save your changes to styles.css and refresh the index.html file in your browser. The <h1> content will now be smaller and uppercased while the <h2> content will be a bit larger and no longer bold. The following screenshot showcases how these changes will appear in the browser:

      Text in dark gray with a heading text that is short bold and uppercase, with other heading text much larger and title cased.

      Classes are a powerful selector, as they can be reused and applied to any element on the page. This means you can swap where and how the style-1 and style-2 classes are used, and no changes need to be made to the CSS.

      To make this change, open index.html and change the class attribute value style-1 on the <h1> element to style-2. Afterward, change the style-2 values on the <h2> elements’ class attribute to style-1. Reference the highlighted sections of the following code block for these changes:

      index.html

      ...
      <header id="header" class="content-width">
        <h1 class="style-2">Using CSS Selectors</h1>
      </header>
      
      <main id="content" class="content-width">
        <section> 
          <h2 class="style-1">Selecting HTML To Style</h2>
          ...
        </section>
      
        <section>
          <h2 class="style-1">The Type Selector</h2>
          ...
        </section>
      
        <section>
          <h2 class="style-1">Combining Selectors</h2>
          ...
        </section>
      </main>
      ...
      

      Save these changes to styles.css, return to your browser, and reload index.html. The large, normal font weight of style-2 is now applied to the content in the <h1> element, and the shorter, uppercase styles of style-1 now apply to the section <h2> elements. The following image shows how this will appear in the browser:

      Text in dark gray with a large title case heading text with other heading text that is short bold and uppercase.

      In this section you used class selectors to refactor the id selectors from the previous section. You also created two new class selectors to apply font styles to the <h1> and <h2> heading elements and you swapped those class attribute values to change which elements received what styles. In the next, section you will continue working with class selectors by applying more than one class to an HTML element.

      Combining Class Selectors

      In this section, you will apply multiple class values to the same HTML element to combine the styles from more than one CSS class selector. The advantage of class over id is its reusability, as shown in the previous section. class selectors can also be combined to target more specific elements. The class selector is the most common and preferred CSS selector for this versatility and specificity in finding an element and applying styles.

      To begin, open your styles.css file in your text editor. Then add three new class selectors: .color-1, .color-2, and .color-3. Each of these three selectors will have a color property with similar HSL values that differ by increments of 50 on the hue spectrum. This will provide a color palette that you can apply to elements in the HTML. See the highlighted portions of the following code block for what to add to your CSS file:

      styles.css

      ...
      .style-2 {
        font-size: 2rem;
        font-weight: normal;
      }
      
      .color-1 {
        color: hsl(300, 70%, 40%);
      }
      
      .color-2 {
        color: hsl(250, 70%, 40%);
      }
      
      .color-3 {
        color: hsl(200, 70%, 40%);
      }
      

      Save your changes to styles.css, then open index.html in your text editor. You will now add a color to each of the three <h2> elements in the <main> block. For the first <h2>, add a space after style-1 and then add color-1. The space between each value in the class attribute indicates an additional class name that can be referenced from the CSS. Do the same for the other <h2> elements, except use the color-2 value for the second <h2> and color-3 for the third <h2>.

      The highlighted portions of the following code block show how to format the additional class values:

      index.html

      ...
      <main id="content" class="content-width">
        <section> 
          <h2 class="style-1 color-1">Selecting HTML To Style</h2>
          ...
        </section>
      
        <section>
          <h2 class="style-1 color-2">The Type Selector</h2>
          ...
        </section>
      
        <section>
          <h2 class="style-1 color-3">Combining Selectors</h2>
          ...
        </section>
      </main>
      ...
      

      Save your changes to index.html, return to your browser, and refresh the page. The three <h2> section headings retain the same font styles, but now each have a different color. The following image shows how this will appear in your browser:

      Three short bold uppercase headings with one magenta, one dark blue, and one teal.

      Just as class values can be used together in HTML, the class names can also be combined to create more specific situations that may be present in the HTML. By chaining together class names in the CSS, you can select elements that have both classes at the same time.

      For example, the CSS selector .color-1.color-2 would only select elements that have an HTML class value that contains both color-1 and color-2.

      To try using multiple class names in a selector, open styles.css in your text editor. Create a new selector that combines the color-1 class and the color-2 class. The intent with this combination is to apply a color that is halfway between the defined color value of each of these classes.

      Add the following highlighted sections to your CSS file:

      styles.css

      ...
      .color-3 {
        color: hsl(200, 70%, 40%);
      }
      
      .color-1.color-2 {
        color: hsl(275, 70%, 40%);
      }
      
      .color-2.color-3 {
        color: hsl(225, 70%, 40%);
      }
      

      In this code block, you set the color property of the combined class selector .color1.color-2 to hsl(275, 70%, 40%), since that is halfway between the 300 value of .color-1 and the 250 value of .color-2. Then you did the same to combine .color-2 and .color-3.

      Be sure to save your changes to styles.css, then move over to index.html in your text editor and make the highlighted changes in the following code block:

      index.html

      ...
      <main id="content" class="content-width">
        <section> 
          <h2 class="style-1 color-1 color-2">Selecting HTML To Style</h2>
          ...
        </section>
        ...
        <section>
          <h2 class="style-1 color-3 color-2">Combining Selectors</h2>
          ...
        </section>
      </main>
      ...
      

      Note that the new styling you declared for the combined class selectors will take precedence over the style set for each of the individual classes. This is because the combined class selector is selecting a more specific element than the individual class selectors. For example, the rule you wrote for .color-1 is looking for an HTML element that has color-1 as one of its classes. The .color-1.color-2 rule is looking for an HTML element that has both color-1 and color-2 in the list of its classes. Since the second rule is a subset of the first, it can be said to be more specific, and thus overrides the first.

      With the two combined class CSS rules you have written, there are situations in which both rules could apply. For example, an HTML element with a class value of color-1 color-2 color-3 would satisfy both the .color-1.color-2 and .color-2.color-3 rules. In this case, since they both have the same amount of specificity, the cascade would come into effect, and the last rule declared would override the styling. In this case, .color-2.color-3 would apply its styling, since it is the final rule declared.

      Save the changes to index.html and then refresh the page in your browser. The colors of all three <h2> elements will still be distinct, but will now be visually closer together in hue.

      The following screenshot shows how this will appear in the browser:

      Three short bold uppercase headings with one purple, one dark blue, and one a medium blue.

      This section presented you with a way to string class values together to create more specific scenarios in which to apply styles. In the next section, you will learn how to find an element on the page based on any attribute type.

      Using the Attribute Selector

      In this section, you will use the attribute selector to find and select an element. In the previous sections, you have learned that the id and class selectors have a symbol indicating the kind of attribute to target followed by a value to select. The attribute selector’s format consists of the name of the attribute wrapped in a pair of square brackets, like so: [attr]. The attribute selector can be used with any attribute, including id and class.

      To begin using an attribute selector, open the index.html file in your text editor. You will add the HTML element for abbreviations, <abbr>, as a situation where attribute selectors would be beneficial. Place the <abbr> around the first instance of CSS in the <h1> element. Then, place another <abbr> around the first instance of HTML in the first <h2> element. With the HTML <abbr>, add a title attribute with a value of Hypertext Markup Language. Reference the following code block for how this will be formatted:

      index.html

      ...
      <h1 class="style-2">Using <abbr>CSS</abbr> Selectors</h1>
      ...
      <h2 class="style-1 color-1 color-2">Selecting <abbr title="Hypertext Markup Language">HTML</abbr> To Style</h2>
      ...
      

      Save your changes to index.html, then return to your browser to load the file. If you are using Chrome or Firefox, the browser default for <abbr> elements with a title attribute is to add a dotted underline. The purpose of the visual indicator is to have a user hover over the text, at which point the meaning of the abbreviation, the title attribute’s value, will appear. The following image demonstrates the default <abbr> styling in Firefox:

      Short bold uppercase headings in purple with an abbreviation text with a dotted underline.

      Unlike Chrome and Firefox, some browsers, like Safari and other older browsers, do not have an indicator of when an <abbr> element has a title. This same styling can be brought to these other browsers, along with some customizations with the attribute selector.

      To begin styling with an attribute selector, open the styles.css file in your text editor. Add an attribute selector for How To Select HTML Elements Using ID, Class, and Attribute Selectors in CSS and then curly brackets for the selector block. In the selector block, add the text-decoration property set to underline. Then add the text-decoration-style property with a value of dotted. These two properties will equalize the styling across browsers. Lastly, to add a custom look for the underline, add the property text-decoration-color and set it to a light gray with the value hsl(0, 0%, 70%).

      Reference the following code block for how this will be formatted in your code:

      styles.css

      ...
      .color-2.color-3 {
        color: hsl(225, 70%, 40%);
      }
      
      How To Select HTML Elements Using ID, Class, and Attribute Selectors in CSS {
        text-decoration: underline;
        text-decoration-style: dotted;
        text-decoration-color: hsl(0, 0%, 70%);
      }
      

      Save your changes to styles.css, then return to your browser and refresh index.html. The styling for the HTML text will now have a light gray dotted underline. The following image demonstrates how this will appear in the browser:

      Short bold uppercase headings in purple with an abbreviation text with a light gray dotted underline.

      The one issue with using the How To Select HTML Elements Using ID, Class, and Attribute Selectors in CSS attribute as a selector is that it can be used on almost any element on the page. This means, with the current selector in place, <img> or <a> elements with the title attribute would also receive these styles. In this case, the selector needs to be scoped to work only with the <abbr> element.

      To make this adjustment to the selector, return to styles.css in your text editor. To the left of the How To Select HTML Elements Using ID, Class, and Attribute Selectors in CSS attribute selector, add the abbr element selector. Be sure there is no space between these selectors as this tells the browser to specifically look for an <abbr> element with a title attribute. The following code block demonstrates how this will look, with the added element selector highlighted:

      styles.css

      ...
      abbrHow To Select HTML Elements Using ID, Class, and Attribute Selectors in CSS {
        text-decoration: underline;
        text-decoration-style: dotted;
        text-decoration-color: hsl(0, 0%, 70%);
      }
      

      Save your changes to styles.css. The styles are now scoped to only work with <abbr> elements with a title attribute. The CSS <abbr> in the <h1> element will not receive these styles either. Though it does match the abbr selector, it does not have a title attribute and so does not match.

      In this section, you used the attribute selector to scope styles to an <abbr> element to apply styles when a title attribute is present. In the next section, you will use more advanced capabilities of the attribute selector by matching the value of a given attribute.

      Creating Advanced Attribute Selectors

      The attribute selector is useful for finding particular attributes in the HTML and applying styles to them. However, the attribute selector also has several ways to look for the value of an attribute. In this final section, you will use the attribute selector to look for matching value strings and apply styles that meet these specific conditions.

      To begin, open your styles.css file in the text editor. In the HTML there is a link that goes to the website https://example.com; to target that specific URL link, create an attribute selector for an href attribute. Then, within the brackets following the attribute name, add an equal sign followed by string quotes. Within those quotes, add https://example.com. This selector will target a link that goes to the specified URL. Add a color property with a green color using hsl(150, 70%, 40%).

      The highlighted code in the following code block shows how this is formatted in your styles.css file:

      styles.css

      ...
      abbrHow To Select HTML Elements Using ID, Class, and Attribute Selectors in CSS {
        text-decoration: underline;
        text-decoration-style: dotted;
        text-decoration-color: hsl(0, 0%, 70%);
      }
      
      [href="https://example.com"] {
        color: hsl(150, 70%, 40%);
      }
      

      Save these changes to styles.css and return to your browser to refresh index.html. Only the link that goes to https://example.com has changed to the color green, while the other link on the page remains the default blue. The following image demonstrates how this will appear in the browser:

      Link text in green color with underline.

      Next, return to styles.css in your text editor and add a custom hover state by using the :hover pseudo selector. The selector is set up the same as the previous selector, and immediately follows after the closing square bracket with :hover. Then within the selector add a color property with a darkened version of the previous green by changing the lightness value of the HSL from 40% to 20%.

      Reference the highlighted code in the following code block for how to format this in your code:

      styles.css

      ...
      [href="https://example.com"] {
        color: hsl(150, 70%, 40%); 
      }
      
      [href="https://example.com"]:hover {
        color: hsl(150, 70%, 20%);
      }
      

      Save your changes to styles.css and then reload index.html in your browser. The link that goes to https://example.com now has a hover state that switches to a darker green, as demonstrated in the following animation:

      Animation of green text link with underline changing to dark green when cursor hovers text.

      The attribute selector has additional condition modifiers to look for particular scenarios within a value string. One of these conditions that an attribute can look for is if a value starts with a given string. This is represented with the ^ symbol between the attribute name and the equal sign. This approach can be used to highlight links that are secure, meaning they go to a URL that begins with https:// instead of http://.

      Return to styles.css in your text editor and add an attribute selector that looks for a value that begins with a secure URL by using [href^="https://"]. This selector will only match elements that have an href element that begins with https://. Then, to add a visual indicator that the link is secure, use a pseudo element selector by adding ::before immediately following the closing bracket. Lastly, the ::before pseudo element selector requires a content property to be used, which will add a string before the content of the HTML element. For the value of this content property, use the unicode identifier for the lock emoji, 1F512.

      The highlighted section of the following code block demonstrates this syntax:

      styles.css

      ...
      
      [href^="https://"]::before {
        content: '1F512';
      }
      

      Save your changes to styles.css and return to your web browser to reload index.html. The two links in the content both have secure links and are now indicated as such with the lock emoji, as demonstrated in the following image:

      Links in two different styles with lock emoji preceding the link text.

      In this section you used the advanced features of the attribute selector to look for specific strings in the HTML attribute’s value. There are more options available for attribute value scenarios than were covered here. If you want to learn more about the different attribute selector options, read The Skinny on CSS Attribute Selectors by Chris Coyier.

      Conclusion

      Writing styles that are specific and reusable is a cornerstone to effective CSS architecture. In this tutorial, you learned how and when to use the id selector, how you can use and reuse the class selector in multiple combinations, and how to use the attribute selector and some of its features to create very specific scenarios in which to add styling. These selectors are a powerful asset to create styles that bring life and functionality to a website.

      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 Use Links and Buttons with State Pseudo-Classes in CSS


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

      Introduction

      An important part of web development is providing feedback when a user interacts with an element. This interaction is accomplished through changing state, which indicates how the user is using or has used a given element on the page. In CSS, there are special variations on selectors called a pseudo-class, which allow state changes to initiate style changes.

      In this tutorial, you will use the :hover, :active, and :focus user actions and the :visited location pseudo-classes. You will use <a> and <button> as the interactive elements in the tutorial. Both of these elements have similar interactive states and are functionally identical to the user. From a development standpoint, <a> elements are specifically for interacting with URLs, whereas the <button> element is used to trigger forms or JavaScript functions. In addition to working with these four distinct states, you will use the transition property to animate the styles between these states of interactivity.

      Prerequisites

      Setting Up the Initial HTML and CSS

      To begin working with links and buttons, you will first set up the HTML and CSS needed as a foundation for the tutorial. In this section, you will write out all the necessary HTML and some initial CSS styles that will handle layout and start the visual aesthetic.

      To begin, open index.html in your text editor. Then, add the following highlighted HTML to the file:

      index.html

      <!doctype html>
      <html>
        <head>
        </head>
        <body>
        </body>
      </html>
      

      Next, go to the <head> tag and add a <meta> tag to define the character set for the HTML file. Then set the title of the page, add a <meta> tag defining how mobile devices should render the page, and finally load the CSS file with a <link> tag. These additions are highlighted in the following code block. You will encounter this highlighting method throughout the tutorial as code is added and changed:

      index.html

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

      After adding the <head> content, next move to the <body> element where content is added to make an informational block with <a> and <button> tags as interactive elements. Add the highlighted section from this code block to your index.html file in your text editor:

      index.html

      <!doctype html>
      <html>
        <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <title>Link and Buttons with State</title>
          <link rel="stylesheet" href="https://www.digitalocean.com/community/tutorials/styles.css">
        </head>
        <body>
          <section>
            <header>
              <button class="link" type="button">
                Close Window
              </button>
            </header>
            <div>
              <p>
                This is a demo paragraph for some demo content for a tutorial. By reading this text you are now informed that this is text for the demo in <a href="https://do.co/tutorials">this tutorial</a>. This means you can agree to use this content for the demo or not. If you wish to continue with this tutorial demo content, please select the appropriately styled interactive element below.
              </p>
              <div>
                <button class="button" type="button">
                  Yes, Please
                </button>
                <a class="button" href="https://www.digitalocean.com/community/tutorials/#">
                  No, Thank you
                </a>
              </div>
            </div>
          </section>
        </body>
      </html>
      

      Save your changes to index.html and open your web browser to open the index.html file there. The content of the page will appear in a black serif font on a white background. The <button> element styles will vary based on your browser and operating system, but the page will look similar to the following image:

      Black serif text on a white background with two blue underlined links and two interactive butons.

      Next, create a file called styles.css in the same directory as the index.html file. The following styles in the code block will set up a base style for the container holding the <button> and <a> elements you will be styling throughout the remainder of the tutorial. Add the following code to your styles.css file:

      styles.css

      body {
        background-color: #454545;
        color: #333;
        font-family: sans-serif;
        line-height: 1.5;
      }
      
      section {
        margin: 2rem auto;
        width: 90%;
        max-width: 50rem;
        box-sizing: border-box;
        padding: 2rem;
        border-radius: 2rem;
        border: 0.25rem solid #777;
        background-color: white;
      }
      
      header {
        text-align: right;
      }
      

      The CSS in this code block adds styles for three portions of the demo content area. The first is the body selector, which applies a dark gray background and then defines default font properties. The second selector focuses on the <section> element, which is the primary container for the demo content and creates a white block with big, rounded corners and a maximum width so it will only grow to a specified amount. Lastly, the header element selector sets the text alignment to the right so the Close Window button is to the far top right corner of the <section> container.

      If you’d like to learn more about how to use CSS element selectors, check out How To Select HTML Elements to Style with CSS.

      Save your changes to the styles.css file and reload the index.html file in your browser. The page styles will have transformed from the browser defaults to a customized style, as demonstrated in the following image:

      Black sans serif text in a white container with rounded corners with two blue underlined links and two interactive butons.

      You have set up your HTML and loaded in the base styles for the contents of the page. Next you will create a custom default link style and provide a way for that default style to be applied to button elements.

      In this section, you will create a custom default link style by setting a new color. Then you will remove default button styles in order to make the button look like a default link. a and button have distinct purposes, but website users interact with both in a similar way. Sometimes, these two elements need to appear similar to help explain an interaction to the user or match a design aesthetic.

      For the first part of this section, you will set up the default link style that will be used on the generic <a> element and a class of .link, which can then apply the generic link styles to the <button> element. Start by creating a group selector containing an a element selector and a .link class selector with a color property and value of #25a:

      styles.css

      ...
      a,
      .link {
        color: #25a;
      }
      

      Save your changes to styles.css and open index.html in your browser. The <a> elements on the page are now a deeper blue color than the browser default link blue. Also, the <button> element with the class="link" has the same blue color text in the button. The appearance of change in the browser is demonstrated in the following image:

      Black sans serif text in a white container with rounded corners with two blue underlined links and two interactive buttons.

      Next, begin removing the default appearance of a button. By default, browsers add a lot of customization to the look and feel of <button> elements to make sure that they are distinguishable as interactive elements. To remove the extra styling that browsers add to these elements, return to styles.css in your text editor, create a button element selector, and add two similar properties as shown in the following code block:

      styles.css

      ...
      a,
      .link {
        color: #25a;
      }
      
      button {
        -webkit-appearance: none;
        appearance: none;
      }
      

      The first property is -webkit-appearance: none;, which is known as a vendor prefix property. The -webkit- position of the property is only read by browsers built on a derivative of the WebKit browser engine, such as Safari or Chrome. Some versions of these browsers don’t support the appearance property by themselves and need the -webkit- prefix in order to work.

      Vendor prefix usage is on the decline, but still occurs. It is important to put any vendor prefixed properties before the non-prefixed to avoid overriding properties on browsers that support both the prefixed and non-prefixed variants.

      Save your changes to styles.css and refresh index.html in your browser. The button element will not lose all its styles; instead, it will become simplified to default styles expected of the web specification. The following image demonstrates how this will appear in the browser:

      Black sans serif text in a white container with rounded corners with two blue underlined links and two interactive buttons.

      To remove the remaining default styles of the button, you will need to add several more properties. Return to your styles.css file in your text editor and go to the button selector. Next, you will add the properties to remove the background-color, border, margin, and padding. Then you’ll remove the properties for the button element, color, font, and text-align, to inherit the value of the page.

      The following code block demonstrates how to set this up:

      styles.css

      ...
      button {
        -webkit-appearance: none;
        appearance: none;
        background-color: transparent;
        border: none;
        margin: 0;
        padding: 0;
        color: inherit;
        font: inherit;
        text-align: center;
      }
      

      Save these changes to styles.css and refresh index.html in your web browser. Both buttons have now lost their default styles, with the Close Window button being closer in styles to the link. The Yes, Please button styles will be addressed in the next section. The following image demonstrates how this will appear in the browser:

      Black sans serif text in a white container with rounded corners with two blue underlined links and two interactive buttons that appear as plain text.

      To finish making the Close Window button look like a text link, open styles.css in your text editor. Below the a, .link group selector, add a new class selector for only the .link class. Add to that a text-decoration property with a value of underline. Then add a property called cursor, which defines how the mouse cursor appears when on that element, and set the value to pointer. The pointer value styles cursor is the hand-style that appears over a link by default:

      styles.css

      ...
      a,
      .link {
      ...
      }
      
      .link {
        text-decoration: underline;
        cursor: pointer;
      }
      ...
      

      Save these changes to your styles.css file and then return to your browser and refresh index.html. The Close Window button will now appear and behave in a similar manner to the generic <a> element styles. The following animation demonstrates how the cursor changes when moving over the Close Window button:

      A button styled to look like a defaul link with blue text and underlined.

      In this section, you created a custom default style for the <a> element and created a .link class to apply link styling to a <button> element. In the next section, you will create a custom, button-like style that can be applied to both <button> and <a> elements.

      Creating Styles for a Button

      Next, you will create a custom, button-like style with a class selector so the styles can be used on either a <button> or an <a> element. Unlike <a> elements, which are used throughout text content, the <button> element has a more intentional purpose. This makes it less necessary to create generic styles for the <button> element, and instead allows you to always add a class attribute.

      Start by opening up styles.css in your text editor. Create a new class selector called .button. The styles here will redefine many of the properties that were reset in the previous step on the button element selector. You will add color to the text with the color property, fill the shape with the background-color property, then provide some definition with the border property. Afterward you will give a rounded corner to the button with the border-radius property. Finally, you will use the padding shorthand to give space above and below the text, then double that amount on the left and right.

      The following code block contains these values:

      styles.css

      ...
      .button {
        color: #25a;
        background-color: #cef;
        border: 1px solid #67c;
        border-radius: 0.5rem;
        padding: 0.75rem 1.5rem;
      }
      

      Save your changes to styles.css and return to your browser to refresh the index.html file. The look of the Yes, Please and No, Thank you buttons will change to match the properties. The text is the same blue as the default a style, with a much lighter blue in the background, and another deep blue for the border. The next image demonstrates how this will appear in the browser:

      Text with two buttons below with one button taller than the other. The shorter button has underlined text.

      There is a noticeable difference in size between the two buttons. Since the No, Thank you button is using an <a> element instead of a <button>, there are a few additional properties that need to be added to the .button selector to equalize the defaults between these two elements.

      Return to styles.css in your text editor and go to the .button class selector. To begin, add a display: inline-block, which is the default style on button elements. Next, add a text-decoration: none to remove the underline from the <a> element. As you did with the .link selector, add a cursor: pointer to the selector to get the pointing hand icon when a mouse cursor is over the element. Lastly, add a vertical-align: bottom rule. This last property isn’t necessary for all browsers, but it defines where the bottom of elements are positioned on a line:

      styles.css

      ...
      .button {
        color: #25a;
        background-color: #cef;
        border: 1px solid #67c;
        border-radius: 0.5rem;
        padding: 0.75rem 1.5rem;
        display: inline-block;
        text-decoration: none;
        cursor: pointer;
        vertical-align: bottom;
      }
      

      Save these additions to styles.css and then refresh index.html in your browser. The two buttons are now equivalent in visual appearance and have borrowed default attributes from one another, so they are perceived to have a similar interaction.

      Text with two light blue button of equal height with dark blue text and a dark blue thin border.

      You created a custom class selector to style both <button> and <a> elements with a button-like style in this section. Next, you will create a conditional style when a mouse cursor is on top of the interactive elements.

      Now you will use the :hover pseudo-class to create an alternative style that displays when the cursor is on the element. Pseudo-classes are a special group of conditions that are defined by a colon (:) and the name of the condition appended to the selector. For example, the a element selector with a hover pseudo-class becomes a:hover.

      Open styles.css in your text editor. Below the group selector for a, .link, add a new selector for the hover state by appending each selector with the :hover pseudo-class: a:hover, .link:hover. Then, to make a noticeable change when the cursor hovers over the element, add a color property with a value of #b1b, which is a dark pink color:

      styles.css

      ...
      a,
      .link {
        ...
      }
      
      a:hover,
      .link:hover {
        color: #b1b;
      }
      ...
      

      Save the changes to your styles.css file and refresh index.html in your browser. Hover over either the this tutorial link or the Close Window button to initiate the color change on hover. The following image shows what the hover state looks like when the cursor is over the this tutorial link.

      A paragraph of text with a link with a hand cursor icon over the link. The link text is a dark pink color with an underline.

      Next, to add a hover state to the .button elements, return to styles.css in your text editor. Below the .button class selector, add a .button:hover selector to create styles specifically for hover interaction. Next, within the selector, add color properties that will change the button appearance when the cursor is on the buttons. Set a color property to white, then create a background-color and a border-color with both properties set to #25a:

      styles.css

      ...
      .button {
        ...
      }
      
      .button:hover {
        color: white;
        background-color: #25a;
        border-color: #25a;
      }
      

      Save these changes to your styles.css file and return to your browser to refresh the index.html file. Now, take your mouse cursor and hover over one of the two buttons on the bottom. The styles change from the light blue background with a deep blue text and border to a deep blue background with white text. The following image shows what the hover style looks like when the mouse cursor is over the Yes, Please button.

      Two buttons below a paragraph of text. One button has a hand pointer cursor over it and is a dark blue with white text. The other button is light blue with dark blue text.

      You used the :hover pseudo-class in this section to create style changes to the element based on the cursor being positioned on top of the element. In the next section, you will apply this same concept to a condition when a keyboard is used to navigate through the page.

      Applying the :focus Pseudo-Class

      Instead of using a mouse or a touch screen, website visitors will sometimes use their keyboard to navigate and interact with elements of a page. This is most often done by using the TAB key, which will cycle through the interactive elements on the page. The default style uses the outline property to give a visual indicator that the element has focus. This style can be customized by using the :focus pseudo-class to apply property values for this situation.

      To begin working with the focus state of the elements on the page, open your styles.css file in your text editor. Start with a new selector below the a:hover, .link:hover group selector with a new group selector for the focus state: a:focus, .link:focus.

      The most important part of customizing the focus state is to make sure it is noticeably different from the default state. Here, you will make the :focus pseudo-class styles have black text with a gold background:

      styles.css

      ...
      a:hover,
      .link:hover {
        ...
      }
      
      a:focus,
      .link:focus {
        color: black;
        outline: 2px solid gold;
        background-color: gold;
      }
      ...
      

      In this case, you set the color property to black and the background-color property to gold. You also used the outline property, which added some gold color around the edges of the text, outside where the background-color property can reach.

      The outline property works similar to the border shorthand property, as it accepts a width, a style, and a color. However, unlike the border properties, outline always goes around the whole element and can not be set to a specific side. Also, unlike border, the outline does not affect the box-model; the shape is only applied visually and does not change the flow of content.

      Save your changes to styles.css and refresh index.html in your web browser. Begin pressing the TAB key until the browser brings focus to the Close Window and this tutorial elements highlight with a gold background. The following image shows what the this tutorial link looks like in the browser when it has focus:

      A paragraph of text with a link. The link text is black color with an underline and a yellow background.

      Next, to apply a similar custom focus style to the .button class elements, begin by creating a .button:focus class and pseudo-class selector. Since the .button element is already using a border, you will use that to indicate focus, and so remove the outline default by setting the property to have a value of none. Like the link before, the color property will be set to black and the background-color property will be set to gold. Last, set the border-color property to have a value of black:

      styles.css

      ...
      .button:hover {
        ...
      }
      
      .button:focus {
        outline: none;
        color: black;
        background-color: gold;
        border-color: black;
      }
      

      Be sure to save your additions to styles.css and then return to you browser to refresh your index.html file. Again, using the TAB key, cycle through the keyboard-focusable elements on the page until you reach the .button elements. They will now light up with a gold background and black text with a black border. The following image demonstrates how the Yes, Please button appears in the browser when focused:

      Two buttons below a paragraph of text. One button is focused with black text and black border with a yellow background. The other button is light blue with dark blue text.

      In this section, you used the :focus pseudo-class to create custom styles that appear when the website visitor uses their keyboard to navigate the page. In the next section, you will use the :active pseudo-class to indicate when a user is interacting with an element via a mouse click or a keypress.

      Applying the :active Pseudo-Class

      The next pseudo-class that you will work with is the :active state of an interactive element. The active state is the state at which an element is interacted with, typically via a mouse down or mouse click action. This provides the opportunity to give the visitor a clear state to indicate a successful mouse click and button press.

      To begin working with the :active pseudo-class, open styles.css in your text editor. Following the group selector block for a:focus, .link:focus, add a new selector block with the group selector a:active, .link:active. Give color a value of #808, which will create a darker pink than the :hover state.

      Note that some browsers will mix the styles of a :focus pseudo-class and an :active pseudo-class. To prevent this, you will need to remove the outline and background-color properties by setting them to none and transparent, respectively:

      styles.css

      ...
      a:focus,
      .link:focus {
        ...
      }
      
      a:active,
      .link:active {
        color: #808;
        outline: none;
        background-color: transparent;
      }
      ...
      

      Save the addition of the :active pseudo-class to your styles.css file, then reload index.html in your web browser. The following animation shows how the :active state changes from the pink to darker pink as the mouse is clicked while over the this tutorial link.

      An animation involving a paragraph of text with a link with a hand cursor icon over the link. The link text is underlined and is alternating between a dark pink and a darker pink.

      Next, to apply an active state to .button, return to styles.css in your text editor. Add a .button:active pseudo-class selector and apply styles that are dark variants of the :hover styles. For the color property, set the value to a light gray with #ddd. For both the background-color and border-color properties, set the value to a dark blue with a value of #127. The highlighted sections of the following code block demonstrate how this is written:

      styles.css

      ...
      .button:focus {
        ...
      }
      
      .button:active {
        color: #ddd;
        background-color: #127;
        border-color: #127;
      }
      

      Be sure to save these changes to styles.css, then return to your browser to refresh index.html. Hover your mouse cursor over one of the two buttons in the bottom of the content and then click down. The button will change from a light blue background with blue text and border to a full blue button with white text when hovered, then to a dark blue button with light gray text when clicked. The following animation demonstrates how this change from the :hover to the :active state appears as the mouse button is clicked:

      An animation of cursor pressing a button turning the button from blue with white text to a dark blue with light gray text.

      You created a visual indicator of a mouse button press event by using the :active pseudo-class to change the styles when that event occurs. In the next section, you will use the :visited pseudo-class to provide an indicator of which <a> elements with a href attribute have visited that link.

      Applying the :visited Pseudo-Class

      The :visited pseudo-class is unlike the previous pseudo-classes covered in this tutorial. Where the previous pseudo-classes involve an active interaction of the user with the element, the :visited pseudo-class indicates that an element was previously interacted with. Specifically, the :visited pseudo-class indicates which <a> with an href attribute are present in the browser history, meaning those links have been visited.

      To create a customized :visited indicator on the text links, open your styles.css file in your text editor. Below the a:active, .link:active group selector, add a new group selector targeting a a:visited, .link:visted group selector. The default :visited link style is commonly a purple color. For the purposes of the demo, the :visited color will be a dark green.

      Add a color property with a value of #080, as shown in the following highlighted code:

      styles.css

      ...
      a:active,
      .link:active {
        ...
      }
      
      a:visited,
      .link:visited {
        color: #080;
      }
      ...
      

      Save this change to the styles.css file and then open index.html in your web browser. If you haven’t, go ahead and click the this tutorial and No, Thank you <a> element links. Both of these links will have a text color of dark green, as shown in the following image:

      Pragraph of text with a visited link underlined and green and two buttons below. One of the button’s text is green instead of dark blue.

      Now, the green text in the button distracts from the purpose of the No, thank you button. Additionally, when the visited links are interacted with again with a :hover or :active state, the dark green remains instead of the defined colors for each respective state.

      To address these scenarios, return to your styles.css file in your text editor. First, append the a:hover, .link:hover group selector with the added scenario of a :visited element that has an active :hover state by adding a:visited:hover, .link:visited:hover. Likewise, expand the a:active, .link:active selector block with a:visited:active, .link:visited:active. Lastly, the desired visited state for the .button element is to be styled the same as the default state. As such, the .button selector needs to become a group selector of .button, .button:visited, so the visited state appears the same as the default state:

      styles.css

      ...
      a:hover,
      .link:hover,
      a:visited:hover,
      .link:visited:hover {
        color: #b1b;
      }
      ...
      a:active,
      .link:active,
      a:visited:active,
      .link:visited:active {
        color: #808;
      }
      
      a:visited,
      .link:visited {
        color: #080;
      }
      ...
      .button,
      .button:visited {
        ...
      }
      
      .button:hover,
      .button:visited:hover {
        color: white;
        background-color: #25a;
        border-color: #25a;
      }
      ...
      

      Save your changes to the styles.css file and reload index.html in the web browser. The text default :visited link now appears in the desired dark green color, while the button-style link retains the button look. The following image demonstrates how this will appear in the browser.

      Paragraph of text with a visited link underlined and green and two similarly-styled buttons below.

      You used the :visited pseudo-class to create styles specific to when a link is present in the browser history, indicating to the user links that have been visited. This section concludes the work on pseudo-classes and using them to define specific styles for a given state. In the final section of this tutorial, you will use the transition property to create a seamless animation between these different pseudo-class states.

      Using transition to Animate Between States

      When working with states of elements, a shift in styles between the states can be abrupt. The transition property is used to blend and animate the styles from one state to the next state to avoid this abruptness. The transition property is a shorthand property that combines the transition-property, transition-duration, and transition-timing-function properties.

      The transition-property can be any property that has a value calculated between two given values. Colors are included in this, as they are numerical values, even when a color name is used. The transition-duration property is a numeric value for how long the transition should occur. The value for the duration is often represented in seconds, with the s unit, or milliseconds, with the ms unit. Lastly, the transition-timing-function controls how the animation will play out over time, enabling you to make subtle changes to enhance the animation.

      To begin working with the transition property, open your styles.css file and go to the a, .link group selector and the .button, .button:visited group selector. Add a transition property with a value of all 0.5s linear. The all is the value for the transition-property, which tells the browser to animate all the properties that change between the states. The 0.5s is the transition-duration value and equates half a second; this can also be represented as 500ms. Lastly, the linear position is the transition-timing-function value, which tells the browser to move from one value to the next in a constant increment throughout the duration:

      styles.css

      ...
      a,
      .link {
        ...
        transition: all 0.5s linear;
      }
      ...
      .button,
      .button:visited {
        ...
        transition: all 0.5s linear;
      }
      

      Save your changes to styles.css and then open index.html in your web browser. Once the page loads, begin interacting with the link and button elements and pay attention to how the styles animate between the different states. The following animation shows the button style transitioning from the default state to the :hover pseudo-class state:

      Animation of a cursor hovering a button and the button transitions styles from a light blue button with blue text to a blue button with white text.

      To make the animations feel more snappy and natural, return to your styles.css file and adjust the transition property values. For the a,.link group selector, change the duration from 0.5s to 250ms, which is half the duration compared to what it was before. Then change the linear timing function value to ease-in-out. This will create an animation that starts off slow, speeds up in the middle, and slows down to the end. Then, for the .button,.button:visited group selector, change the duration to a quicker 180ms and set the timing function to the same ease-in-out value as the link:

      styles.css

      
      ...
      a,
      .link {
        ...
        transition: all 250ms ease-in-out;
      }
      ...
      .button,
      .button:visited {
        ...
        transition: all 180ms ease-in-out;
      }
      

      Save these changes to your styles.css file and then refresh the index.html page in your web browser. The transition animations between states will still animate, but are now much quicker and feel faster, too. With the transition property, it is important to play around with the values to find an animation that fits the design. The following animation demonstrates the faster transition of the button from the default state to the :hover state to the :active state.

      Animation of a cursor hovering a button and the button transitions styles from a light blue button with blue text to a blue button with white text. Then the cursor moves and hovers a green underlined link and link fades to a pink color.

      You have now created an animation between states. The transition property helps make changes between states more engaging and fun.

      Conclusion

      Providing clear differences between interactive element states is a valuable asset to a website. States help communicate important concepts to the website’s visitor by providing visual feedback to an interaction.

      In this tutorial, you have successfully used the primary state pseudo-classes to create multiple styles for different interactive elements. You also learned that there are different purposes behind the <button> and <a> elements, but visually they can communicate similar concepts. Lastly, you used the transition property to provide smooth animations between these states to create more engaging interactive elements. It is important to keep these four states in mind when creating a website so the visitor is given this important interactive feedback.

      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