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

      Comment créer un style de barre de défilement avec CSS


      Introduction

      En septembre 2018, les barres de défilement CSS de W3C ont défini des spécifications pour personnaliser l’apparence des barres de défilement avec CSS.

      En 2020, 96 % des utilisateurs d’Internet exécutent des navigateurs qui prennent en charge la création de style de barres de défilement CSS. Cependant, afin de couvrir les navigateurs Blink, WebKit et Firefox, vous devrez écrire deux ensembles de règles CSS.

      Au cours de ce tutoriel, vous allez apprendre à utiliser CSS pour personnaliser des barres de défilement qui soient prises en charge par les navigateurs modernes.

      Conditions préalables

      Pour suivre le déroulement de cet article, vous aurez besoin de :

      Créer le style des barres de défilement dans Chrome, Edge et Safari

      Actuellement, vous pouvez utiliser le pseudo-élément du préfixe vendeur -webkit-scrollbar pour créer le style de vos barres de défilement pour Chrome, Edge et Safari.

      Voici un exemple qui utilise les pseudo-éléments ::-webkit-scrollbar, ::-webkit-scrollbar-track et ::webkit-scrollbar-thumb :

      body::-webkit-scrollbar {
        width: 12px; /* width of the entire scrollbar */
      }
      
      body::-webkit-scrollbar-track {
        background: orange; /* color of the tracking area */
      }
      
      body::-webkit-scrollbar-thumb {
        background-color: blue; /* color of the scroll thumb */
        border-radius: 20px; /* roundness of the scroll thumb */
        border: 3px solid orange; /* creates padding around scroll thumb */
      }
      

      Voici une capture d’écran de la barre de défilement obtenue avec ces règles CSS :

      Capture d'écran d'un exemple de page web avec une barre de défilement personnalisée bleue sur un fond orange.

      Ce code fonctionne avec les dernières versions de Chrome, Edge et Safari.

      Malheureusement, cette spécification a été officiellement abandonnée par W3C et sera probablement à éviter au fil du temps.

      Créer le style des barres de défilement dans Firefox

      Actuellement, vous pouvez créer le style des barres de défilement sous Firefox avec les nouveaux CSS Scrollbars.

      Voici un exemple qui utilise les propriétés scrollbar-width et scrollbar-color :

      body {
        scrollbar-width: thin; /* "auto" or "thin" */
        scrollbar-color: blue orange; /* scroll thumb and track */
      }
      

      Voici une capture d’écran de la barre de défilement obtenue avec ces règles CSS :

      Capture d'écran d'un exemple de page web avec une barre de défilement personnalisée bleue sur un fond orange.

      Cette spécification partage quelques points communs avec la spécification -webkit-scrollbar pour contrôler la couleur de la barre de défilement. Cependant, il n’existe actuellement aucune spécification permettant de modifier le remplissage et l’arrondi de la « piste de défilement ».

      Créer des styles de barre de défilement à l’épreuve du temps

      Vous pouvez écrire votre CSS de manière à prendre en charge les spécifications -webkit-scrollbar et CSS Scrollbar.

      Voici un exemple qui utilise scrollbar-width, scrollbar-color, ::-webkit-scrollbar, ::-webkit-scrollbar-track, ::webkit-scrollbar-thumb :

      /* Works on Firefox */
      * {
        scrollbar-width: thin;
        scrollbar-color: blue orange;
      }
      
      /* Works on Chrome, Edge, and Safari */
      *::-webkit-scrollbar {
        width: 12px;
      }
      
      *::-webkit-scrollbar-track {
        background: orange;
      }
      
      *::-webkit-scrollbar-thumb {
        background-color: blue;
        border-radius: 20px;
        border: 3px solid orange;
      }
      

      Les navigateurs Blink et WebKit ignoreront les règles qu’ils ne reconnaitront pas et appliqueront les règles -webkit-scrollbar. Les navigateurs Firefox ignoreront les règles qu’ils ne reconnaitront pas et appliqueront les règles CSS Scrollbars. Une fois que les navigateurs Blink et WebKit ne prendront plus en charge la spécification -webkit-scrollbar, ils reviendront gracieusement à la nouvelle spécification CSS Scrollbars.

      Conclusion

      Au cours de cet article, vous avez été initié à l’utilisation de CSS pour créer le style des barres de défilement tout en veillant à ce que ces styles soient reconnus par la plupart des navigateurs modernes.

      Vous pouvez également simuler une barre de défilement en cachant la barre de défilement par défaut et en utilisant JavaScript pour détecter la hauteur et la position de défilement. Cependant, ces approches présentent des limitations en termes de reproduction d’expériences comme le défilement à inertie (par exemple, mouvement décroissant pendant le défilement avec des pistes de défilement).

      Si vous souhaitez en savoir plus sur CSS, veuillez consulter notre page thématique CSS dans laquelle vous trouverez des exercices et des projets de programmation.



      Source link

      How To Style Text Elements with Font, Size, and Color in CSS


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

      Introduction

      Cascading Style Sheets (CSS) is a language designed for two disciplines: that of the programmer and that of the designer. Working with text on the web is one of the clearest examples of this broad accessibility to the language. Styling text uses concepts from the graphic design world but adjusts naming conventions to be more broadly implemented.

      In this tutorial you will learn about web typography, the art of styling text. Similar to working with a printing press, you will set out your content, apply visual style to help communicate the content, and adjust the content for legibility and emphasis. The intent with styling text on the web is to create a visual hierarchy through color, size, shape, and space. This way, headings stand out from sub-headings, which stand out from paragraphs. These concepts help make text more readable and scannable for readers.

      You will start the tutorial by writing the HTML structure, which will consist of placeholder content from Cupcake Ipsum. You will work with different heading levels (h1h6) and content types (p, strong, and em) to apply multiple text-related CSS properties, including font-family, font-size, and color. You will also load custom fonts from Google Fonts, a third-party font-hosting service. Each step of this tutorial will introduce a new concept or set of properties to apply to the content. By the end you will have a custom-styled web page.

      Prerequisites

      Setting Up the Example HTML

      In this first step you will set up the HTML that you will style throughout the rest of the tutorial. The purpose of the HTML in this tutorial is to provide various elements and situations for you to practice styling.

      Open up the index.html file using a text editor, such as nano, Vim, or Visual Studio Code. Add the following boilerplate HTML to give the file necessary baseline code:

      index.html

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

      The <link /> element already loads in the styles.css file, so be sure to have that file ready as well.

      Next, you need some content to style. When creating text styles, often a project needs styles before the content is ready. In the graphic design world, placeholder content is used for this purpose. Designers will often use Latin text as a placeholder, known as Lorem Ipsum. There are many modern renditions of this placeholder text, including Cupcake Ipsum. This will be the reference copy used throughout the HTML.

      To start, the HTML needs to depict hierarchy, a clear distinction and order of content. In HTML that is done with heading tags, which span from <h1>, the top most heading, through <h6>, the bottom most heading. The browser default styles for the headings define the visual hierarchy by size alone, with the <h1> element’s default font-size being significantly larger than that of the <h6>. Throughout this tutorial you will use other principles of design, such as color and space, to provide visual hierarchy to the content.

      To create this hierarchical content, you will write out various headings and fill each heading with a few words from Cupcake Ipsum within the <body> tags in index.html. You will follow proper HTML semantics, which provide accurate meaning to the browser.

      To have proper HTML semantics:

      • There will only be one <h1> element on the page. This will usually be the title.
      • Subsequent heading levels will only be one lesser, equal, or any greater level. For example, the only heading level that comes after an <h3> will be either <h4>, another <h3>, or an <h2>, but never an <h5> or <h6>.

      With the rules of heading semantics, add the following highlighted HTML to index.html:

      index.html

      ...
        <body>
          <h1>Sugar plum chupa chups chocolate bar cupcake donut</h1>
      
          <h2>Tootsie roll oat cake macaroon</h2>
      
          <h2>Jelly beans tiramisu pastry danish donut</h2>
      
          <h3>Lemon drops pastry marshmallow</h3>
      
          <h3>Apple pie pudding topping</h3>
      
          <h4>Gingerbread danish</h4>
      
          <h5>Carrot cake topping lollipop gummi bears</h5>
      
          <h6>Liquorice bonbon candy cotton candy liquorice</h6>
        </body>
      ...
      

      Next, you need some content to fill in space between each heading. These will be paragraphs of text designated by the <p> element to hold each paragraph. Use Cupcake Ipsum again to generate this content and place the paragraphs throughout the page.

      Add the highlighted portions of the following code block. This tutorial will use this format for code blocks throughout:

      index.html

      ...
        <body>
          <h1>Sugar plum chupa chups chocolate bar cupcake donut</h1>
      
          <h2>Tootsie roll oat cake macaroon</h2>
      
          <p>Jujubes brownie candy. Dessert tootsie roll pie gummi bears danish cotton candy. Sugar plum I love fruitcake pastry. Jelly-o gummi bears muffin gummi bears marzipan cheesecake donut gingerbread I love. Cupcake wafer cake.</p>
      
          <h2>Jelly beans tiramisu pastry danish donut</h2>
      
          <h3>Lemon drops pastry marshmallow</h3>
      
          <p>I love marshmallow candy. Sesame snaps muffin danish. Chocolate cake cookie jelly-o tiramisu halvah brownie halvah chocolate chocolate cake. Jelly-o caramels jujubes bonbon cupcake danish tootsie roll chocolate bar. Macaroon I love muffin candy canes sweet roll I love. I love bonbon marshmallow croissant ice cream I love gummi bears.</p>
      
          <h3>Apple pie pudding topping</h3>
      
          <p>Pie apple pie I love jujubes biscuit I love. Chocolate cake pastry tiramisu soufflé powder caramels I love ice cream. Dragée liquorice toffee jelly jelly beans. Sesame snaps candy canes soufflé. Biscuit donut bear claw jujubes halvah pastry macaroon lemon drops. Tootsie roll dragée cookie candy soufflé dragée cupcake liquorice.</p>
      
          <h4>Gingerbread danish</h4>
      
          <p>Powder dragée sesame snaps candy canes jelly-o. Halvah gingerbread cheesecake wafer. Wafer tootsie roll I love I love. Cake toffee I love. Cotton candy cotton candy jelly beans I love bonbon toffee. Chupa chups chupa chups caramels ice cream halvah candy chocolate cake. Marshmallow carrot cake jelly beans.</p>
      
          <h5>Carrot cake topping lollipop gummi bears</h5>
      
          <p>Chocolate cake sweet roll pudding chocolate cake fruitcake bear claw.</p>
      
          <h6>Liquorice bonbon candy cotton candy liquorice</h6>
      
          <p>Cupcake donut topping chupa chups halvah chupa chups. Macaroon tootsie roll cupcake caramels chocolate fruitcake gingerbread jelly-o. Tiramisu I love marshmallow jelly-o I love jelly beans candy gummi bears.</p>
        </body>
      ...
      

      Finally, add in <strong>, <em>, and a combination of the two elements together. This will provide examples of phrases that are emphasized in the content:

      index.html

      ...
          <h2>Tootsie roll oat cake macaroon</h2>
      
          <p>Jujubes brownie candy. Dessert tootsie roll pie gummi bears danish cotton candy. Sugar plum <strong>I love fruitcake pastry</strong>. Jelly-o gummi bears muffin gummi bears marzipan cheesecake donut gingerbread I love. Cupcake wafer cake.</p>
      
          <h2>Jelly beans tiramisu pastry danish donut</h2>
      
          <h3>Lemon drops pastry marshmallow</h3>
      
          <p>I love marshmallow candy. <em>Sesame snaps</em> muffin danish. Chocolate cake cookie jelly-o tiramisu halvah brownie halvah chocolate chocolate cake. Jelly-o caramels jujubes bonbon cupcake danish tootsie roll chocolate bar. Macaroon I love muffin candy canes sweet roll I love. I love bonbon marshmallow croissant ice cream I love gummi bears.</p>
      
          <h3>Apple pie pudding topping</h3>
      
          <p>Pie apple pie I love jujubes biscuit I love. Chocolate cake pastry tiramisu <strong>soufflé powder caramels</strong> I love ice cream. Dragée liquorice toffee jelly jelly beans. Sesame snaps candy canes soufflé. Biscuit donut bear claw jujubes halvah pastry macaroon lemon drops. Tootsie roll dragée cookie candy soufflé dragée cupcake liquorice.</p>
      
          <h4>Gingerbread danish</h4>
      
          <p>Powder dragée sesame snaps candy canes jelly-o. Halvah gingerbread cheesecake wafer. <strong><em>Wafer tootsie roll</em></strong> I love I love. Cake toffee I love. Cotton candy cotton candy jelly beans I love bonbon toffee. Chupa chups chupa chups caramels ice cream halvah candy chocolate cake. Marshmallow carrot cake jelly beans.</p>
      
          <h5>Carrot cake topping lollipop gummi bears</h5>
      
          <p>Chocolate cake sweet roll pudding chocolate cake fruitcake bear claw.</p>
      
          <h6>Liquorice bonbon candy cotton candy liquorice</h6>
      
          <p>Cupcake donut topping <em><strong>chupa chups halvah</strong></em> chupa chups. Macaroon tootsie roll cupcake caramels chocolate fruitcake gingerbread jelly-o. Tiramisu I love marshmallow jelly-o I love jelly beans candy gummi bears.</p>
      ...
      

      Now that you have the HTML written, save index.html and open it in your browser to see what the page looks like with the browser default styles:

      Content of a web page with several headings and paragraphs all in a black, serif font on a white background.

      The text ranges in sizes across all the elements, with the default <h5> and <h6> styles being smaller than the <p> text.

      In this step you set up the HTML content that will be styled throughout the rest of the tutorial. Next, you will work with the font-family property, learn about the font stack, a list of fonts that the browser can use, and apply fonts to different elements.

      Using the font-family Property

      Next, you will work with the font-family CSS property and load an external font file from the Google Fonts service. The name of this property derives from a typography term that describes the collection of fonts and the variations of that font, including bold and italic versions. A font can have many of these variations, but can all be part of the same font-family, with those variations called with font-weight and font-style properties.

      To begin working with font-family, it is helpful to understand the particulars about its value options. The value of a font-family property is a list of fonts called a font stack. The font stack works as a fallback system. Consider the following font-family property value:

      font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
      

      The browser is first going to determine if Helvetica Neue is available for it to use, either as a font that is installed on the computer or as one provided by a website. If the browser doesn’t find a font called Helvetica Neue, then it goes down the list to Helvetica and then to Arial. If the browser is unable to find any of those fonts, then the last font in the list, sans-serif, will use whatever the browser has set as its default font for a sans-serif style font.

      Note: Font stacks provide their best feature not when a font is not found, but when a particular character is not found in the font. This is especially necessary for instances of using multiple language support, where one font may not have a character set that covers all languages needs. A font stack can contain a fallback font that provides the special characters and a similar visual feel to the primary font in the stack.

      Create a file called styles.css in the same directory as index.html. Open it up in your text editor and add a default font for the page:

      styles.css

      body {
        font-family: "Avenir Next", Calibri, Verdana, sans-serif;
      }
      

      In this code, you start with a body type selector with a font–family property. Next, for the font stack you start with "Avenir Next", which will be available on iOS and macOS browsers. Avenir Next is in quotes because the font name is two words. The next font is Calibri for Windows browsers. Be sure to put a comma between each font declaration. To provide a more generic font fallback, you then use Verdana, which has been widely available on computers since the early 2000s. Finally, since all these fonts are classified as sans serif fonts, you add the browser default sans-serif as the final font option in the font stack.

      Save styles.css, then open up index.html in your browser. You will find a new font in place of the browser default font for the content. If you are on an Apple operating system, Avenir Next will render in the browser. If you are on Windows, Calibri will render instead. The following image is what this font stack looks like on MacOS:

      The content of the web page deplayed with the Avenir Next font in various font weights.

      In this section you used the font-family property to set up a default font stack for the web page. You also set up a font-family property that applies specifically to heading text content. In the next section you will use the Google Fonts service to load a custom font file and use it on the page.

      Loading Custom Fonts With Google Fonts

      Now that you have used the font-family property with fonts already installed on your computer, it is time to load fonts from an external service. This will widen the range of fonts you can use to style your text. In this section, you will work with the Google Fonts service to load and use a font on the web page.

      Browsers have the ability to load any font, so long as it is provided the appropriate font file format for that browser. A font service, such as Google Fonts, alleviates the work of defining and hosting fonts by providing both the CSS and font files needed to load the font. There are many other services like Google Fonts, but Google Fonts hosts royalty and open source fonts and offers the service free of charge.

      To get started, open fonts.google.com in you browser.

      There are many different fonts you can choose from in Google Fonts. This tutorial will use two: Public Sans and Quicksand.

      From the search field on Google Fonts, search for Public Sans. When the font card shows up from the search result, a preview of the font is displayed. Click the card to go to the page for the font:

      Google Fonts page for the Public Sans font, displaying the font at different weights.

      The Public Sans font page will list all the variations of the font. These are known as weights, which range from 100 to 900. For the purposes of this tutorial, find the Regular (400) and the Bold (700) styles and press the + Select this style button next to each style variant, as well as their italic style.

      Once you select the first style, a selected family tool will slide in. This tool will provide you with the HTML and CSS needed to use these fonts:

      Selected font family tool, with the HTML and CSS lines needed to use Public Sans.

      Select the <link /> method to load the fonts in the browser and copy the provided HTML. Open index.html and add the code into the <head> element after the <link /> loading styles.css. Keep Google Fonts open, as you will return to it a couple more times:

      index.html

      ...
      <head>
          <link href="https://www.digitalocean.com/community/tutorials/styles.css" rel="stylesheet" />
          <link href="https://fonts.googleapis.com/css2?family=Public+Sans:ital,wght@0,400;0,700;1,400;1,700&display=swap" rel="stylesheet">
      </head>
      ...
      

      At this point, reloading index.html in your browser won’t have any visual changes. The browser is loading the font, but the font needs to be added to the font stack to apply the font to the content.

      Return to Google Fonts to find the CSS rule that loads Public Sans. Google Fonts provides a font stack of Public Sans and the browser default sans-serif font with font-family: 'Public Sans', sans-serif;. Since you already have a font stack set up with fallback fonts, all that you need to take from Google Fonts’ example is the name to reference Public Sans.

      Using your existing font stack in styles.css, replace Avenir Next and Calibri with Public Sans:

      styles.css

      body {
        font-family: "Public Sans", Verdana, sans-serif;
      }
      

      Now that the base font stack has been declared all fonts on the page are now Public Sans.

      One common design practice to bring more attention to headings is to use a different font for the headings than for the main text. To apply this to your own HTML, return to Google Fonts and do a search for “Quicksand.” This will be the heading, or display font, for the <h1> through <h6> elements on the page.

      Once you have found Quicksand, select the font card and add the Semi-bold (600) and Bold (700) font weights to the selected fonts alongside Public Sans. Google Fonts will provide a new URL to load all the selected fonts and variants. Swap out the previous href value for the new link in your index.html file:

      index.html

      ...
      <head>
          <link href="https://www.digitalocean.com/community/tutorials/styles.css" rel="stylesheet" />
          <link href="https://fonts.googleapis.com/css2?family=Public+Sans:ital,wght@0,400;0,700;1,400;1,700&family=Quicksand:wght@600;700&display=swap" rel="stylesheet">" rel="stylesheet">
      </head>
      ...
      

      Now that Quicksand is set to load in the browser, you need to apply it to the heading tags. You will accomplish this by adding a comma-separated list of CSS selectors, called a group selector, to your styles.css file. In this case, use the font stack provided by Google Fonts with Quicksand followed by the browser default sans-serif font:

      styles.css

      ...
      h1, h2, h3, h4, h5, h6 {
        font-family: "Quicksand", sans-serif;
      }
      

      Save your changes to styles.css and return to your browser to reload index.html. Feel free to close Google Fonts at this point. When the browser loads, you will now find two fonts displayed. Quicksand is now on all the headings and Public Sans is on all other content, including the bold and italic content.

      The content of the website using fonts loaded from Google Fonts.

      In this section you loaded two fonts from the Google Fonts service and added those fonts to your existing font stacks. The next section will look at using the font variants to specify when and how to apply bold and italic to a font.

      Using font-weight and font-style Properties

      In this section you will use the font-weight and font-style properties to adjust how a font appears. There are many reasons to use these variations, such as to emphasize content, as part of a citation style guide, and to provide visual variation.

      Now that you are loading in custom fonts from Google Fonts, you can start to fine-tune the characteristics of the text. Starting with the font-weight property, you can change how thick or thin the font is displayed. The font-weight property has two common values: normal and bold. The normal value is the default font-weight for most text in a browser. The bold value is the default font-weight for headings and <strong> elements. But for this tutorial, you will need to use the numeric values instead of the name normal and bold values.

      Numeric font-weight values depend on the font that you are loading. When you added the Public Sans font from Google Fonts, you selected the Regular (400) and the Bold (700) weights. The numbers in parenthesis coincide with the values needed to reference and load that font. Additionally, the font-weight value of 400 is the numerical equivalent of normal, like 700 is the numerical equivalent of bold. Text that uses Public Sans, which is all but the headings, will automatically use these weights.

      Alternatively, the Quicksand font selections included the Semi-bold (600) and Bold (700) font weights. The 600 value does not have a numerical counterpart and needs to be defined using a numerical value.

      You will start by setting the font-weight of all headings to the 600 semi-bold variant of Quicksand. In your styles.css file, locate the group selector with all the heading values and add a font-weight: 600; declaration to the selector block:

      styles.css

      ...
      h1, h2, h3, h4, h5, h6 {
          font-family: "Quicksand", sans-serif;
          font-weight: 600;
      }
      

      Once you have made this change, save styles.css and reload index.html in your browser. You will see a slight thinning of the headings as they change from the 700 value of Quicksand to the 600 value.

      Now that you have set all the heading elements to use the Quicksand 600 weight, there are still places to use the 700 variation of the font. To start, create an h3 type selector in your styles.css file and add font-weight: 700; in the selector block:

      styles.css

      ...
      h3 {
          font-weight: 700;
      }
      

      This change will cause the h3 to stand out a bit as it is now bolder than the other headings. As the tutorial progresses, you will make additional changes to the h3 styles to make it stand out but still maintain its hierarchical order.

      Save your changes to styles.css and then create a new selector that targets text that is wrapped in both <em> and <strong> tags. In the case of the styles written so far, this kind of text will get the bold italic variant of Public Sans. Instead, set the styles to use the Quicksand font stack.

      Since the HTML to get a bold italic style is <strong><em>...</em></strong> and <em><strong>...</strong></em>, you will need to create a combinator group selector in your styles.css file and then apply the font-family property with "Quicksand", sans-serif as the value:

      styles.css

      ...
      strong em,
      em strong {
          font-family: "Quicksand", sans-serif;
      }
      

      Once you have made this addition to your styles.css file, save it and then reload index.html in your browser. The text that was bold italic now is using Quicksand and is italic, even though Google Fonts is not providing an italic version of the font. This is called a faux italic, where the browser understands that this content should be italic by default, but since an italic variation is not defined is instead artificially slanting the text.

      The property for handling whether text is italicized or not is font-style. The value options for the font-style property are normal and italic. Instead of using the faux bold, change the styles for this selector to have no italicization. Add to the strong em, em strong group selector in your styles.css file the font-style property with a value of normal:

      styles.css

      ...
      strong em,
      em strong {
          font-family: "Quicksand", sans-serif;
          font-style: normal;
      }
      

      This will change the instance of bold italic text to be only Quicksand bold.

      Save your changes to styles.css and reload index.html in your browser to see the change:

      The last sentence from the website content with text that is bold italic being bold only in the Quicksand font.

      You used the font-weight and font-style properties in this section to apply variations of the Quicksand font loaded from Google Fonts. Next, you will use the font-size property to create larger, more legible text with clearer hierarchy amongst the headings.

      Using the font-size Property

      In this section you will use the font-size property to apply different font sizes to the content throughout the page. The size of text is an important factor in communicating information. Well-sized text is easier to read and appropriately sized headings help convey hierarchy for easier skimming of the information. You will change the font-size of all the elements you created in index.html to create a document that is more readable.

      Start by setting a default font-size on the body element. The default browser font-size is 16px, but it can be helpful for increased legibility for many fonts to be just a little bigger. Open your styles.css file and add a font-size: 18px; to the body element:

      styles.css

      body {
          font-family: "Public Sans", Verdana, sans-serif;
          font-size: 18px;
      }
      ...
      

      Open index.html in your browser or refresh the page. The font-size change on the body element changed all the fonts on the page, increasing their size.

      The default font sizes for elements are relatively sized based on the parent element, in this case the <body> element, using a percent value for the font size. Using the formula (target / base) * 100% will give you a percentage value that is relative to the base font size set on the <body> element.

      To give this formula a try, you will work with setting a target font-size for the <h1> element to be 45px. Using the formula, the target size is 45px and the base size is 18px, so the formula for this will be (45 / 18) * 100%, which comes to 250%. This means that the intended size for the <h1> will be 2.5 times the size of the base font-size.

      Return to you styles.css file and add an element selector for h1 and add a font-size: 250%; property and value to set the font size:

      styles.css

      ...
      h1 {
          font-size: 250%;
      }
      ...
      

      Now that you have set a relative font size for the <h1> element, apply the same formula to the remaining heading elements. With each you can choose to either round, or keep the full decimal values. It can also be helpful to leave comments explaining the target size or even the formula.

      Open up your styles.css file and start by adding a comment after the h1 font-size property explaining the rendered size. Then for each heading apply the formula so the h2 has a font-size equivalent of 36px, the h3 equal to 32px, h4 to 26px, the h5 to 22px, and lastly the h6 to the base size of 18px. The default size of the <h6> element is smaller than the base size, so setting it to 100% will ensure that it does not go below the base value:

      styles.css

      ...
      h1 {
          font-size: 250%; /* 45px */
      }
      
      h2 {
          font-size: 200%; /* 36px */
      }
      
      h3 {
          font-size: 177.78%; /* 32px */
      }
      
      h4 {
          font-size: 162.5%; /* 26px */
      }
      
      h5 {
          font-size: 122%; /* 22px */
      }
      
      h6 {
          font-size: 100%; /* 18px */
      }
      ...
      

      Return to your browser and refresh index.html. All the headings will increase their font-size based relatively on the default font-size set on the <body> element. The following image shows how this change will render in a browser:

      The content of the website in black text with custom font sizes throughout with the main heading being 2.5 times larger than the base text size.

      With this step you used the font-size property to change the size of the text on the web page. You used the design concept of size to give hierarchy to the content beyond the default browser styles. In the next step, you will take the design of the content further with the color property.

      Using the color Property to Distinguish Text

      The focus of the next section is the color CSS property, using color to differentiate order and add meaning to the content. Color is one of the most common design considerations, in particular with defining different meaning to text. In this section you will use named colors to set your text color. Named colors are a collection of predefined colors that has grown over the years; they match to other web color values, such as hexadecimal color codes. This section will use the named color list found on Wikipedia’s page on Web colors. You may want to keep the Wikipedia Web colors page open in your browser for reference.

      Like you did with font-size, you are going to set a default color to the whole document. This will affect all content on the page, as color is an inherited value for most elements. It is important to keep color contrast in mind, as it helps legibility, especially when it comes to making the web accessible to all levels of vision. Since the background-color will remain the default white, using bold, darker colors is a good guide. If you wish to learn more about designing with accessible color contrast, watch this short video series on the topic.

      To begin using color, return to your styles.css file in your text editor. As you did with the font-size section, find the body selector and add a color property. The default color for text in most browsers is black. For accessible color contrast, it is important to keep the base color dark when on a light background. Use the named color DarkSlateGray, which is only camel case here for legibility, but can be all lowercase if you wish:

      styles.css

      body {
          font-family: "Public Sans", Verdana, sans-serif;
          font-size: 18px;
          color: DarkSlateGray;
      }
      ...
      

      Save your styles.css file and refresh index.html in your browser. The color of the content will change from black to a dark blue-green:

      A portion of the content of website on a white background with a dark blue-green color.

      Now that the base color is set, you can start using other colors to provide more visual hierarchy. Start with the h1 selector in your styles.css file and add a color property with a value of Indigo:

      styles.css

      ...
      h1 {
          font-size: 250%; /* 45px */
          color: Indigo;
      }
      ...
      

      Save your styles.css file, return to your browser, and refresh index.html. The <h1> text now has a deep purple color instead of the default dark blue-green color:

      The main heading of the page in a dark puple color.

      Next, you will apply colors to the other headings. Quicksand is a fun, rounded font and you’re using the quirky Cupcake Ipsum sample content, so create a bright and peppy color scheme by using a different color on each heading. Return to styles.css and, for each of the heading selectors, add a color property and color value. For the h2 element use MediumVioletRed, for the h3 use LimeGreen, for the h4 add Chocolate, for the h5 use Crimson, then finally for the h6 use DeepSky Blue:

      styles.css

      ...
      h2 {
          font-size: 200%; /* 36px */
          color: MediumVioletRed;
      }
      
      h3 {
          font-size: 177.78%; /* 32px */
          color: LimeGreen;
      }
      
      h4 {
          font-size: 162.5%; /* 26px */
          color: Chocolate;
      }
      
      h5 {
          font-size: 122%; /* 22px */
          color: Crimson;
      }
      
      h6 {
          font-size: 100%; /* 18px */
          color: DeepSkyBlue;
      }
      ...
      

      Once you have added the color properties to the headings, save styles.css and return to the browser to refresh index.html. Your content is now full of color:

      The full final page with various colored text on a white background with different font sizes.

      With the color property you learned about web color named values and how you can use color to provide meaning. You also used the color property to give the content personality by adding a colorful palette to the content of the web page.

      Conclusion

      Working with text is a major part of writing CSS for the web. Text conveys meaning not only in what it says, but also in how it looks. Using the tools you have learned with the font-family, font-weight, font-style, font-size, and color properties, you can manipulate text to help provide meaningful context to your website. These properties are not limited to the headings covered in this article: they can be used with any element containing text.

      If you would like to read more CSS tutorials, check out our CSS topic page.



      Source link