One place for hosting & domains

      Elements

      How To Apply Background Styles to HTML Elements with CSS


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

      Introduction

      When building a website, background styling plays a large role in the visual aesthetic of the design. Whether you are building out a button or a large interactive area, background styles provide definition and can distinguish areas for particular purposes. Understanding what is possible with the background family of properties in CSS will help you create more efficient code and visually interesting designs.

      In this tutorial, you will create a grid of elements, each showcasing different ways of applying a background to the element. By creating a grouped series of examples, you will end up with a reference tool and a place to experiment with different background properties. You will create a sheet of 18 background color, image, and gradient variations. Each variation will use background-related properties to achieve a particular effect. The last variation will combine many approaches on a single element, creating a multiple-background effect.

      Grid of background image demos consisting of 3 columns and 6 rows.

      Prerequisites

      Setting Up the Initial HTML and CSS

      To start working with background styling, 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 set the groundwork for the visual aesthetic.

      Begin by opening 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. Set the title of the page, add a <meta> tag defining how mobile devices should render 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>Background Styles Resource</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 a title and the base <div> for our grid. 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>Background Styles Resource</title>
          <link rel="stylesheet" href="https://www.digitalocean.com/community/tutorials/styles.css" />
        </head>
        <body>
          <h1>Background Styles Resource</h1>
          <div class="grid">
          </div>
        </body>
      </html>
      

      The <h1> provides a heading describing the contents of the page. The <div> element with the grid class attribute will contain all the remaining HTML added throughout the tutorial.

      Save your changes to index.html and leave it open in your text editor. Then, go ahead and open index.html in your web browser. During the tutorial, you will switch back and forth between your text editor and your browser to verify the changes made to your code.

      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: system-ui, sans-serif;
        color: #333;
      }
      
      h1 {
        text-align: center;
      }
      

      The body element selector changes the font for the page from the default serif to the operating system’s font, if supported, and then falls back to a sans-serif font. The h1 selector centers the text on the page.

      Next, you will add a CSS Grid, a collection of comprehensive layout properties, to the .grid class selector. The highlighted CSS of the following code block indicates what will be added to styles.css:

      styles.css

      ...
      h1 {
        text-align: center;
      }
      
      .grid {
        width: 90%;
        max-width: 80rem;
        margin: 2rem auto;
        display: grid;
        grid-template-columns: repeat(3, minmax(100px, 1fr));
        grid-gap: 1.5rem;
      }
      

      The properties on this selector will set a flexible width with a max-width so you can resize the page and have the width adapt. It will also set a margin property to set space above and below the grid. Then you will apply the properties needed to define the grid.

      The display property makes the element use CSS grid with the grid value. Once that is set, the other two properties, grid-template-columns and grid-gap, will now affect the contents of the .grid element, which you will add later. The grid-template-columns states that there will be 3 columns and that they must have a minimum width of 100px and a maximum width of 1fr (fraction) of the whole width. Since there are three columns, that fraction will be 33.333%. Lastly, the grid-gap defines that between each row and column of the grid, there is 1.5rem spacing.

      Next, you will add two more class selectors for HTML you will write in later sections. Add an .item class selector, which will apply to grid items of each variation. Then, add a .preview class selector, which will contain the background style demo. The highlighted CSS in the following code block demonstrates how to set this up:

      styles.css

      ...
      .grid {
        ...
      }
      
      .item {
        border: 1px solid #999;
        background-color: white;
      }
      
      .preview {
        height: 16rem;
        border-bottom: 1px solid #999;
      }
      

      You have now set up the starting points for your index.html and styles.css files. Be sure to save the changes to both files before continuing.

      For the last part of the setup for this tutorial, create a new directory (or folder) alongside your index.html and styles.css files called images. Download each of the following images and add them to this newly created images directory:

      In this section you prepared the HTML and CSS that will support your code throughout the rest of the tutorial. You also downloaded demo images and added them to an images directory alongside your index.html and styles.css files. In the next section, you will set a background-color and a background-image.

      Using background-color and background-image on Elements

      You can fill an HTML element with one of two types of backgrounds: a color or an image. CSS-generated gradients are a type of image, and will be covered later in the tutorial. In this section, you will work with applying a color background to an element and then load an image file as a background on an element.

      Start by opening index.html in your text editor and adding the highlighted HTML from the following code block inside the <div class="grid"> element:

      index.html

      ...
      <div class="grid">
        <div class="item">
          <div class="preview style-01"></div>
          <div class="item-info">
            <h2>Background Color</h2>
          </div>
        </div>
      </div>
      ...
      

      You will use this HTML format for each variation you create throughout the tutorial. What will change from variation to variation is the class attribute value, which will increment the number for each variation. The <h2> element will have a corresponding title for that variation.

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

      After the .preview class selector, add a new class selector called .style-01. Then, in the new selector block, add a background-color property with a named value of deeppink. The highlighted CSS in the following code block shows how this will look:

      styles.css

      ...
      .preview {
        height: 16rem;
      }
      
      .style-01 {
        background-color: deeppink;
      }
      

      Save your changes to styles.css and then return to your web browser and refresh index.html. You will now have a pink image in the first variation, as shown in the following image:

      Solid pink color

      The background-color property will accept any valid CSS color, including colors that have an alpha channel, such as RGBA and HSLA. You can use the alpha channel to provide transparency to the background color.

      Next, return to index.html and add a new variation, this time incrementing the class to style-02. Also set the <h2> element’s text to Background Image. The highlighted HTML in the following code block demonstrate how this will appear in your file:

      index.html

      ...
      <div class="grid">
        ...
        <div class="item">
          <div class="preview style-02"></div>
          <div class="item-info">
            <h2>Background Image</h2>
          </div>
        </div>
      </div>
      ...
      

      Save your changes to index.html, then open styles.css in your text editor. Add a .style-02 class selector, then add a background-image property. To load the photo.jpg file as the background, first create a url() function as the value. Then, inside the parentheses of the url() function, add a path to the file, as the highlighted CSS in the following code block demonstrates:

      styles.css

      ...
      .style-01 {
        ...
      }
      
      .style-02 {
        background-image: url("./images/photo.jpg");
      }
      

      Save your changes to styles.css and then refresh index.html in your web browser. The preview area will only display a portion of the photo.jpg image, as the image’s size is larger than the size of the preview area. A background image, by default, is shown at its original pixel dimensions, leading to an image that is not fully visible. The following image demonstrates how this will appear in your browser:

      Out of focus portion of the hummingbird photo

      In this section you set up your first two background variations. The first used a background-color property, and the second used the background-image property. Next, you will create four variations to use different values for the background-repeat property.

      Tiling Images With the background-repeat Property

      Now that you can load background images onto an element, you will now work with different ways of tiling images with a repeating pattern image. By default, a background-image repeats as a tiled pattern along the x- and y-axis, but you can control that repetition to only repeat along a single axis, or to not repeat at all. In this section, you will use the background-repeat property to control four different repeating scenarios.

      First, open index.html in your text editor and add a new item to the grid with a class of style-03 and an <h2> with Background Repeat. The highlighted HTML from the following code block shows how this will appear in your file:

      index.html

      ...
      <div class="grid">
        ...
        <div class="item">
          <div class="preview style-03"></div>
          <div class="item-info">
            <h2>Background Repeat</h2>
          </div>
        </div>
      </div>
      ...
      

      Next, save your changes to index.html and open styles.css in your text editor. Create a class selector for .style-03. Inside the selector block, add a background-image with a url() function that loads the pattern.png image from your images folder, as highlighted in the following code block:

      styles.css

      ...
      .style-02 {
        ...
      }
      
      .style-03 {
        background-image: url("./images/pattern.png");
      }
      

      Save your changes to styles.css and then return to your web browser and refresh index.html. The pattern.png image will be set up as a repeatable tile that looks like an unending image that fills the whole element. The style for this element will appear in the browser as shown in the following image:

      Repeating pattern of orange and pink circles connected by blue and purple lines on a white background.

      It is important to note that this image is repeating from the top left corner and expanding continuously toward the right and bottom. This is the default state of any background-image, which can create a seamless pattern like this or a more rigid repetition. The property creating this default is background-repeat set to a value of repeat.

      With the background-repeat property, you also can create a seamless pattern repeating only from the left to the right. There are all kinds of effects that can use this kind of repeat, such as a jagged shape along the top of the container like a torn perforated edge. You could also use this to make a stylized double line graphic span from end to end on the bottom. By setting the background-repeat property to repeat-x, you can tell the browser to repeat the background along only the x-axis.

      To start working along the x-axis, return to index.html in your text editor. Then, add a new HTML block to the grid with a class of style-04 and an <h2> with Background Repeat X. The highlighted HTML from the following code block demonstrates how this will appear in your file:

      index.html

      ...
      <div class="grid">
        ...
        <div class="item">
          <div class="preview style-04"></div>
          <div class="item-info">
            <h2>Background Repeat X</h2>
          </div>
        </div>
      </div>
      ...
      

      Save your changes to index.html and open styles.css in your text editor. Create a .style-04 class selector with a background-image property loading the pattern-x.png file in your images directory. This image is designed to repeat along the top x-axis of the element. Next, add a background-repeat property with a value set to repeat-x, as highlighted in the following code block:

      styles.css

      ...
      .style-03 {
        ...
      }
      
      .style-04 {
        background-image: url("./images/pattern-x.png");
        background-repeat: repeat-x;
      }
      

      Save your changes to styles.css and then return to your web browser and refresh index.html. By default, repeating background images start in the top left corner of the element. Thus, the pattern will repeat along the top portion of the preview element’s area from left to right, as shown in the following image:

      Repeating pattern along the top of the image consisting of orange and pink circles connected by blue and purple lines on a white background.

      Just as a background can be set to repeat from left to right, it can also be set to repeat from top to bottom. You can do this by setting the background-repeat property to repeat-y, which will repeat the image along the y-axis in a single column. This can be useful for creating visual effects along the left or right side edge of a container.

      To start using the y-axis, open index.html in your text editor and add a new item to the grid with a class of style-05 and an <h2> with Background Repeat Y. The highlighted HTML from the following code block shows how this will appear in your file:

      index.html

      ...
      <div class="grid">
        ...
        <div class="item">
          <div class="preview style-05"></div>
          <div class="item-info">
            <h2>Background Repeat Y</h2>
          </div>
        </div>
      </div>
      ...
      

      Then, save your changes to index.html and open styles.css in your text editor. As with the x-axis example, create a class selector for .style-05 and add a background-image property. This time, set the background-image value to point to the pattern-y.png image. Then, add the background-repeat property and set the value to repeat-y, as highlighted in the following code block:

      styles.css

      ...
      .style-04 {
        ...
      }
      
      .style-05 {
        background-image: url("./images/pattern-y.png");
        background-repeat: repeat-y;
      }
      

      Save your changes to styles.css and then return to your web browser and refresh index.html. The pattern will now repeat down along the left edge of the preview element, as demonstrated in the following image:

      Repeating pattern along the left side of the image consisting of orange and pink circles connected by blue and purple lines on a white background.

      Often it’s useful to not have a background image repeating at all. This could happen in instances where a visual graphic is added as a background instead of as HTML <img />, such as is done sometimes with logos or icons. The repetition can be disabled entirely by setting the background-repeat property to the no-repeat value.

      To start, return to index.html in your text editor and add another item to the grid with a class of style-06 and an <h2> element with Background No Repeat. The highlighted HTML from the following code block shows how this will appear in your file:

      index.html

      ...
      <div class="grid">
        ...
        <div class="item">
          <div class="preview style-06"></div>
          <div class="item-info">
            <h2>Background No Repeat</h2>
          </div>
        </div>
      </div>
      ...
      

      Save your changes to index.html and open styles.css in your text editor. Add the .style-06 class selector and, as with the first variation of the section, create a background-image property that loads the pattern.png file as the background image. Next, add a background-repeat property set to the value no-repeat. The image will only show once, instead of the continuous tiled repetition. The highlighted CSS of the following code block demonstrates how this will appear in your styles.css file:

      styles.css

      ...
      .style-05 {
        ...
      }
      
      .style-06 {
        background-image: url("./images/pattern.png");
        background-repeat: no-repeat;
      }
      

      Save your changes to styles.css and then return to your web browser and refresh index.html. There will now be a single instance of the pattern.png image in the top left corner of the preview element, as shown in the following image:

      Orange circle connecting to four pink quarter circles via a purple and a blue line in the top left portion of the image.

      In this section you used the background-repeat property’s default value of repeat. You also repeated a tiled image horizontally with the repeat-x value and vertically with the repeat-y value. Lastly, you prevented an image from repeating at all with the no-repeat value. In the next section, you will use the background-position property to set where on the element the background image is anchored.

      Adjusting Placement of a Background Image With background-position

      When working with background-image, it is important to know that images are positioned in the top left corner of the element by default. However, that might not be where you want to set the background image within the element, especially if the image does not repeat. In this section, you will use the background-position property to change where the initial instance of the image is anchored in the element.

      To begin working with background-position, open index.html in your text editor and add a new item to the grid with a class of style-07 and an <h2> with Background Position. The highlighted HTML from the following code block shows how this will appear in your file:

      index.html

      ...
      <div class="grid">
        ...
        <div class="item">
          <div class="preview style-07"></div>
          <div class="item-info">
            <h2>Background Position</h2>
          </div>
        </div>
      </div>
      ...
      

      Next, save your changes to index.html and open styles.css in your text editor.

      Create a class selector for .stlye-07. For each of the CSS blocks in this section, load the pattern.png file for the background-image and set the background-repeat property to no-repeat, so that the positioning is more identifiable. Lastly, add a background-position property and use the named values of bottom right together to anchor the image to the adjacent corner from the default. The highlighted CSS of the following code block indicates how this is to be written:

      styles.css

      ...
      .style-06 {
        ...
      }
      
      .style-07 {
        background-image: url("./images/pattern.png");
        background-repeat: no-repeat;
        background-position: bottom right;
      }
      

      Save your changes to styles.css and then return to your web browser and refresh index.html. There is now a single instance of the pattern.png file displaying in the bottom right corner of the preview element, as shown in the following image:

      Orange circle conntecting to four pink quarter circles via a purple and a blue line in the bottom right portion of the image.

      The background-position property can accept two named values, one for each axis. For the x-axis, these values are left, center, and right. For the y-axis, the values are top, center, and bottom. The center named value is present for both axes and can be combined to position a background image in the absolute middle of an element.

      To center a background image, start by opening index.html in your text editor and add a new item to the grid with a class of style-08 and an <h2> element with Background Position Center. The highlighted HTML from the following code block shows how this will appear in your file:

      index.html

      ...
      <div class="grid">
        ...
        <div class="item">
          <div class="preview style-08"></div>
          <div class="item-info">
            <h2>Background Position Center</h2>
          </div>
        </div>
      </div>
      ...
      

      Next, save your changes to index.html and open styles.css in your text editor. Create a .style-08 class selector and add the background-image property loading pattern.png and the background-repeat property set to no-repeat as with the previous variation. You can set the background-position property to a single named value of center and the browser will understand to use this name for both the x- and y-axis positions. The highlighted CSS of the following code block shows how this is set up:

      styles.css

      ...
      .style-07 {
        ...
      }
      
      .style-08 {
        background-image: url("./images/pattern.png");
        background-repeat: no-repeat;
        background-position: center;
      }
      

      Save your changes to styles.css and then return to your web browser and refresh index.html. The single instance of pattern.png is now floating in the center of the preview element, as shown in the following image:

      Orange circle connecting to four pink quarter circles via a purple and a blue line in the center of the image.

      You can also use numeric values along with named values to define a starting position for a background-image. This can be useful when you want to offset the background image from the element’s edge by a set or relative amount.

      First, return to index.html in your text editor and add another item to the grid with a class of style-09 and an <h2> element with Background Position Numeric. The highlighted HTML from the following code block shows how this will appear in your file:

      index.html

      ...
      <div class="grid">
        ...
        <div class="item">
          <div class="preview style-09"></div>
          <div class="item-info">
            <h2>Background Position Numeric</h2>
          </div>
        </div>
      </div>
      ...
      

      Save your changes to index.html and open styles.css in your text editor. Next, create a .style-09 class selector with a background-image property that loads the pattern.png file and a background-repeat property with the no-repeat value. Then, add a background-position property with a value of right 10% bottom 40px, as highlighted in the following code block:

      styles.css

      ...
      .style-08 {
        ...
      }
      
      .style-09 {
        background-image: url("./images/pattern.png");
        background-repeat: no-repeat;
        background-position: right 10% bottom 40px;
      }
      

      The right 10% portion of the background-position property will anchor the background-image 10% of the element’s width from the right. Then, the bottom 40px will set the background-image 40px from the bottom of the element.

      Save your changes to styles.css and then return to your web browser and refresh index.html. The pattern image will now be in the bottom right portion of the element, but with some spacing from the edges, as shown in the following image:

      Orange circle connecting to four pink quarter circles via a purple and a blue line near the bottom right portion of the image.

      In this section, you used the background-position property to anchor a background image to various positions using word values, such as bottom and center, as well as numeric values combined with the word values. In the next section, you will use the background-size property to resize a background image within the element.

      Resizing a Background Image With the background-size Property

      Images loaded as backgrounds on an element are placed at their full pixel dimensions. For example, if the image file used for the background has a pixel dimension of 800⨉600, but the element it is applied to is 400⨉300, then 25% of the background image will be visible. In this section, you will use the background-size property to resize a background-image file.

      To begin resizing a background-image, open index.html in your text editor. Then, add a new item to the grid with a class of style-10 and an <h2> with Background Size Contain. The highlighted HTML from the following code block shows how this will appear in your file:

      index.html

      ...
      <div class="grid">
        ...
        <div class="item">
          <div class="preview style-10"></div>
          <div class="item-info">
            <h2>Background Size Contain</h2>
          </div>
        </div>
      </div>
      ...
      

      Next, save your changes to index.html and open styles.css in your text editor.

      Create a class selector for .style-10. Inside the selector block, load the photo.jpg image of a hummingbird as the background-image. Next, set the background-repeat property to no-repeat and the background-position to center, so you only have one iteration of the image centered to the element. Lastly, add a background-size property and use the named value contain, as highlighted in the following code block:

      styles.css

      ...
      .style-09 {
        ...
      }
      
      .style-10 {
        background-image: url("./images/photo.jpg");
        background-repeat: no-repeat;
        background-position: center;
        background-size: contain;
      }
      

      Save your changes to styles.css and then return to your web browser and refresh index.html. The image will now be scaled down to be fully contained within the element, as the background-size named value of contain implies. The image of a hummingbird is now fully visible, whereas without the background-size only a fraction was displayed. The following image demonstrates how this will appear in your browser:

      An Anna’s Hummingbird with its beak in a flower. The whole image is contained in the element.

      Next, you will set the background-size value to resize so it fully covers the element’s background space. Start by opening index.html in your text editor and add another item to the grid with a class of style-11 and an <h2> element with Background Size Cover. The highlighted HTML from the following code block shows how this will appear in your file:

      index.html

      ...
      <div class="grid">
        ...
        <div class="item">
          <div class="preview style-11"></div>
          <div class="item-info">
            <h2>Background Size Cover</h2>
          </div>
        </div>
      </div>
      ...
      

      Save your changes to index.html and open styles.css in your text editor. Next, create a .style-11 class selector and copy over the same background-image, background-repeat, and background-position properties from the .style-10 selector block. Then, add a background-size property using the named value cover. The highlighted CSS in the following code block demonstrates how to write this in your text editor:

      styles.css

      ...
      .style-10 {
        ...
      }
      
      .style-11 {
        background-image: url("./images/photo.jpg");
        background-repeat: no-repeat;
        background-position: center;
        background-size: cover;
      }
      

      Save your changes to styles.css and then return to your web browser and refresh index.html.

      The background-image will now fill the whole element, but be scaled down to fit. The cover value will resize the background-image according to the orientation of the element. If the element is a landscape orientation, meaning it is wider than it is tall, then the background-image will be resized so the width is the same as the element. This causes the height of the background-image in this case to be taller than the element and therefore cut off by the bounds of the element. The following image demonstrates how background-image with a background-size of cover will appear in the browser:

      An Anna’s Hummingbird with its beak in a flower. The image fills the whole element, with some content cut off at the top and bottom.

      Lastly, the background-size value can also accept numeric values. To use a numeric value, return to index.html in your text editor. Next, add a new item to the grid with a class of style-12 and an <h2> element with Background Size Numeric. The highlighted HTML from the following code block shows how this will appear in your file:

      index.html

      ...
      <div class="grid">
        ...
        <div class="item">
          <div class="preview style-12"></div>
          <div class="item-info">
            <h2>Background Size Numeric</h2>
          </div>
        </div>
      </div>
      ...
      

      Next, save your changes to index.html and open styles.css in your text editor. Create a .style-12 class selector. Once again, copy over the same background-image, background-repeat, and background-position properties used on .style-10 and .style-11 and add them to the selector block for .style-12.

      Then, add the background-size property with a numeric value of 30%. When you provide the background-size property as a single numeric value, it will apply the same value to both the height and width of the image. To maintain the image’s aspect ratio, add the word auto after the 30%, which will then set the image’s width to 30% and set the height in proportion. The highlighted CSS indicates how the .style-12 selector block and properties will appear in your text editor:

      styles.css

      ...
      .style-11 {
        ...
      }
      
      .style-12 {
        background-image: url("./images/photo.jpg");
        background-repeat: no-repeat;
        background-position: center;
        background-size: 30% auto;
      }
      

      Save your changes to styles.css and then return to your web browser and refresh index.html. The image of the hummingbird is now proportionally scaled by 30% of its width in the center of the element, as displayed in the following image:

      An Anna’s Hummingbird with its beak in a flower. The image is centered within the element.

      In this section, you used the backround-size property to scale the background image to be fully visible within the element with the contain value. You used the cover property to scale the background image to resize so as much of the image could be shown while covering the whole element. Lastly, you used a numeric value to scale the background image to a set size and used the auto value to keep the scaling proportional. In the next section, you will use the background-attachment property to prevent the background image from scrolling with its element.

      Affixing a Background Image With the background-attachment Property

      The background-attachement property makes a background-image stationary. This creates an effect where the content slides over the image as though it were floating above it. In this section, you will use the background-attachment property to create this effect.

      To begin, open index.html in your text editor and add a new item to the grid with a class of style-13 and an <h2> with Background Attachment. The highlighted HTML from the following code block shows how this will appear in your file:

      index.html

      ...
      <div class="grid">
        ...
        <div class="item">
          <div class="preview style-13"></div>
          <div class="item-info">
            <h2>Background Attachment</h2>
          </div>
        </div>
      </div>
      ...
      

      Next, save your changes to index.html and open styles.css in your text editor.

      Create a .style-13 class selector. In the selector block, add a background-image property that loads the pattern.png file from your images directory. Use this image with the defaults, so that the image repeats to fill the whole element. Lastly, add the background-attachment property with a named value of fixed, as highlighted in the following code block:

      styles.css

      ...
      .style-12 {
        ...
      }
      
      .style-13 {
        background-image: url("./images/pattern.png");
        background-attachment: fixed;
      }
      

      Save your changes to styles.css and then return to your web browser and refresh index.html. As you scroll down the page, the preview area for this variation may seem more like a window looking out to a background behind it. The important thing to consider when using this property is that the image is fixed to the browser viewport, not to the element. This will affect the background-position as it changes the origin point that determines the position. The following animation demonstrates this effect in the browser:

      Animation of a repeating pattern of orange and pink circles connected by blue and purple lines on a white background. As the user scrolls, the element moves but the background is fixed.

      In this section, you used the background-attachment property with the fixed value to prevent the background image from scrolling with its element. In the next section, you will combine all the previous properties into the background shorthand property.

      Combining Properties Into the background Property

      All the CSS properties up to this point can be combined into a single background shorthand property. In this section, you will create two variations using this shorthand property to understand normal usage and the special considerations when applying a background-size value.

      Note: Remember that using the background shorthand can override some property values, even if not explicitly declared. For example, background will override a background-image value even if no image is provided in the shorthand value.

      To begin using the shorthand, open index.html in your text editor and add a new item to the grid with a class of style-14 and an <h2> with Background Shorthand. The highlighted HTML from the following code block shows how this will appear in your file:

      index.html

      ...
      <div class="grid">
        ...
        <div class="item">
          <div class="preview style-14"></div>
          <div class="item-info">
            <h2>Background Shorthand</h2>
          </div>
        </div>
      </div>
      ...
      

      Next, save your changes to index.html and open styles.css in your text editor. Create a .style-14 class selector and add the background shorthand property in the selector block. For the value, add a url() function that loads pattern.png from your images directory. After the function, add a space and add the named value center, which will apply a background-position value. Next, add another space with the named value repeat-x. Lastly, add a named color value of gold and finish the line with a semicolon, as highlighted in the following code block:

      styles.css

      ...
      .style-13 {
        ...
      }
      
      .style-14 {
        background: url("./images/pattern.png") center repeat-x gold;
      }
      

      Save your changes to styles.css and then return to your web browser and refresh index.html. The pattern.png image is loaded and, due to the center and repeat-x values, is only repeating from left to right in the vertical center of the preview element. Additionally, the preview element is filled with a solid gold color, as shown in the following image:

      Repeating pattern across the center of the image consisting of orange circles and pink half circles connected by blue and purple lines on a yellow background

      For the background shorthand, the values can be in any order. The image does not have to come first, nor does the color need to come last. But there is one exception to this rule when applying a background-size to the shorthand. In this case, the background-size value must come after the background-position value and be separated not by a space but a forward slash symbol (/).

      Return to the index.html file in your text editor. Then, add a new item to the grid with a class of style-15 and an <h2> with Background Shorthand with Size. The highlighted HTML from the following code block shows how this will appear in your file:

      index.html

      ...
      <div class="grid">
        ...
        <div class="item">
          <div class="preview style-15"></div>
          <div class="item-info">
            <h2>Background Shorthand with Size</h2>
          </div>
        </div>
      </div>
      ...
      

      Save your changes to index.html and open styles.css in your text editor. Then, add a .style-15 class selector with a background shorthand property. Use the same url('./images/pattern.png) for the image. Then set the position value to center, followed by a space then a forward slash (/). After the forward slash, add another space then 64px as the value for the background-size. Since a single value is used for the background-size value, both the height and the width of the background image will be set to 64px. Lastly, add a space and the shorthand hexadecimal value for a dark gray: #222. The highlighted CSS shows how this will appear in your styles.css file:

      styles.css

      ...
      .style-14 {
        ...
      }
      
      .style-15 {
        background: url("./images/pattern.png") center / 64px #222;
      }
      

      Save your changes to styles.css and then return to your web browser and refresh index.html. The preview element for this variation will now have the pattern image scaled to approximately half its size and repeating with a dark gray background color. The following image shows how this background style is rendered in the browser:

      Repeating pattern along the top of the image consisting of orange and pink circles connected by blue and purple lines on a dark gray background

      In this section you used the background property, which is a shorthand property combining all of the properties used in this tutorial. In the next section, you will try out a CSS gradient with the linear-gradient() function.

      Creating a Gradient With the linear-gradient Function

      You can supply the background-image property with values other than a url() image file; it can also create gradients. CSS currently has three different gradient functions, linear-gradient(), radial-gradient(), and conic-gradient(). In this section, you will use the linear-gradient() function to create a linear gradient between two colors, as well as a more complex gradient with multiple colors and a defined angle.

      From a design perspective, gradients can have many uses. They provide a visual aesthetic that is more dynamic than a solid color, but not as complex as a photograph. A gradient can also be used with opacity to make a photo more subdued, improving the legibility of any overlaying text.

      First, open index.html in your text editor and add a new item to the grid with a class of style-16 and an <h2> with Linear Gradient. The highlighted HTML from the following code block shows how this will appear in your file:

      index.html

      ...
      <div class="grid">
        ...
        <div class="item">
          <div class="preview style-16"></div>
          <div class="item-info">
            <h2>Linear Gradient</h2>
          </div>
        </div>
      </div>
      ...
      

      Save your changes to index.html and open styles.css in your text editor. Next, create a background-image property. For the value, add the linear-gradient() function. Within the function’s parentheses, start by adding a direction, which can use a word value of to right. This word value tells the browser to draw the gradient from left to right. Next, add a comma followed by the named color deeppink. After that, add another comma and the named color orange, as highlighted in the following code block:

      styles.css

      ...
      .style-15 {
        ...
      }
      
      .style-16 {
        background-image: linear-gradient(to right, deeppink, orange);
      }
      

      Save your changes to styles.css and then return to your web browser and refresh index.html. The browser will draw a gradient with deeppink on the left and transition the color to orange on the right, as shown in the following image:

      Color gradient of pink on the left to orange on the right.

      All gradients allow for multiple color values and stopping points that can be either a fixed value or a percentage. To begin, return to index.html in your text editor and add another item to the grid with a class of style-17 and an <h2> with Linear Gradient with Stops. The highlighted HTML from the following code block shows how this will appear in your file:

      index.html

      ...
      <div class="grid">
        ...
        <div class="item">
          <div class="preview style-17"></div>
          <div class="item-info">
            <h2>Linear Gradient with Stops</h2>
          </div>
        </div>
      </div>
      ...
      

      Next, save your changes to index.html and open styles.css in your text editor. Add a background-image property with a linear-gradient() value. Inside the function’s parentheses, add a direction of 175deg. The linear-gradient() function accepts numeric degree values in addition to word directions. The first color is navy, but before adding a comma for the next color, add a space instead and set this color’s position on the gradient to 0%. Next, add the comma, followed by the color dodgerblue at 35% followed by a comma. Continue this process for skyblue 50%, then gold 50%, which sets a hard line between the two colors. Then finish out the gradient with orange 51% followed by saddlebrown 100%, as depicted in the highlighted CSS in the following code block:

      styles.css

      ...
      .style-16 {
        ...
      }
      
      .style-17 {
        background-image: linear-gradient(175deg, navy 0%, dodgerblue 35%, skyblue 50%, gold 50%, orange 51%, saddlebrown 100%);
      }
      

      Save these changes to styles.css and then refresh the page in your web browser. This progression of colors and stop points creates an intricate gradient that may appear similar to a desert horizon image. The following image shows the rendering of this gradient in the browser:

      Gradient of dark blue to light blue with an immediate change to yellow and orange fading to a light brown, resembling a desert horizon.

      In this section you used the linear-gradient() CSS function to create a two color gradient and a more complex gradient consisting of several colors and stop points. In the last section, you will create multiple backgrounds on one element.

      Mixing an Image With a Gradient Using the Multiple Background Method

      In this last section, you will combine everything you have worked with in this tutorial to apply multiple backgrounds to a single preview element. Multiple backgrounds can help create visually complex styles while using a minimal amount of HTML elements.

      To start, open index.html in your text editor and add the last item to the grid with a class of style-18 and an <h2> with Multiple Backgrounds. The highlighted HTML from the following code block shows how this will appear in your file:

      index.html

      ...
      <div class="grid">
        ...
        <div class="item">
          <div class="preview style-18"></div>
          <div class="item-info">
            <h2>Multiple Backgrounds</h2>
          </div>
        </div>
      </div>
      ...
      

      Next, save your changes to index.html and open styles.css in your text editor. Create a .style-18 class selector and add a background property. Since multiple backgrounds can get long, it can be helpful to put the property values on their own line separate from the property name. For this first part, load the hummingbird image again, photo.jpg. Then add center / cover no-repeat, which will center the image to the element and scale the image to fill the space while not repeating the image. The highlighted CSS in the following code block demonstrates how to write this in your text editor:

      styles.css

      ...
      .style-17 {
        ...
      }
      
      .style-18 {
        background:
            url("./images/photo.jpg") center / cover no-repeat
        ;
      }
      

      Save these changes to styles.css, then return to your web browser and refresh the page. The hummingbird image will be centered in the element and scaled to fit, as shown in the following image:

      An Anna’s Hummingbird with its beak in a flower. The image covers the whole element.

      Multiple background images are layered as they are read by the browser. To add a gradient above the image of the hummingbird, the gradient will need to come before the image in the background value. Each layer of the multiple backgrounds is separated by a comma, which allows multiple sets of background shorthand values.

      In order to add a gradient overlaying the hummingbird image, return to your styles.css file and to the .style-18 selector. Add a new line between the background property and the url("./images/photo.jpg") center / cover no-repeat. Then, add a linear-gradient() with a word direction of to top left in the parentheses. Add a comma followed by dodgerblue 10%, then transparent 80%. Lastly, after the closing parenthesis of the linear-gradient() add another comma to distinguish it as a multiple background, as demonstrated in the following highlighted code:

      styles.css

      ...
      .style-18 {
        background:
          linear-gradient(to top left, dodgerblue 10%, transparent 80%),
          url("./images/photo.jpg") center / cover no-repeat
        ;
      }
      

      Save your changes to styles.css and then refresh index.html in your web browser. The gradient overlays the hummingbird image progressing from a full blue in the bottom right corner to transparent in the top left corner, as rendered in the browser in the following image:

      An Anna’s Hummingbird with its beak in a flower with a gradient fade to blue.

      Next, you’ll add one more background overlay of repeating images down the left side of the preview element.

      Return to styles.css in your text editor and add a new line after the background: property. Use the url() function to load in pattern-y.png from the images directory. After this, set the position of the background to be center left and add a forward slash to set the size of the background image to 64px. Lastly, set the background to repeat-y so that it repeats vertically and end the background set with a comma. The highlighted CSS in the following code block demonstrates how this is written:

      styles.css

      ...
      .style-18 {
        background:
          url("./images/pattern-y.png") center left / 64px repeat-y,
          linear-gradient(to top left, dodgerblue 10%, transparent 80%),
          url("./images/photo.jpg") center / cover no-repeat
        ;
      }
      

      Save your changes to styles.css and then return to your web browser and refresh index.html. The new top layer background is the pink and orange dot pattern on the left side of the element. The pattern is overlaying both the gradient and the hummingbird image, as shown in the following image:

      An Anna’s Hummingbird with its beak in a flower with a gradient fade to blue, with a repeating pattern along the left side of the image consisting of orange and pink circles connected by blue and purple lines on a white background.

      In this section, you used the skills you developed in preceding sections to apply multiple backgrounds to a single element. Multiple backgrounds are a useful tool for creating intricate styles without extra HTML overhead. This same effect without multiple background would take at minimum three HTML elements with several additional styling properties in order to have the elements layered on top of one another and have the same dimensions.

      Conclusion

      In this tutorial, you ran through examples of many properties to control how a background is presented on an HTML element. You applied solid colors, loaded image resources, and created gradients. You adjusted how an image tiles and repeats on an element and resized background images to fit differently in the space. You also combined all of these properties into the background shorthand and composed multiple backgrounds. Out of this tutorial, you created a resource you can reference again and again on how to work with and combine these many background properties to create something new.

      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 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