One place for hosting & domains

      Apply

      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 Apply CSS Styles to HTML with Cascade and Specificity


      Introduction

      Cascading Stylesheets, better known as CSS, is the language for visual style and design on the web. CSS has a long history on the web dating back to 1994 with the initial idea. In the time since, CSS has become a feature-rich language capable of laying out a webpage, creating complex animations, and much more.

      Since CSS is the web’s styling language, understanding how it works and how to use it is fundamental to web development. It is especially valuable to understand in order to work with Hypertext Markup Language (HTML) and JavaScript effectively. This tutorial will focus on applying CSS to HTML, cascade, and specificity, which are foundational aspects of CSS and will prepare you for using CSS effectively in your web projects.

      CSS is not a conventional programming language. While it does have some features found in other programming languages, such as variables and math, CSS is wholly dependent on HTML to work. CSS’s purpose is to provide visual modifications to HTML. The CSS language is more like a to-do list for the browser: You are saying to the browser, here is a list of things I want you to find. Once the browser finds those things, the CSS instructs the browser to go through the subset list and make changes to those things.

      The browser follows this list of instructions from top to bottom unquestionably, and CSS needs to be written with that in mind. The cascade part of Cascading Stylesheets speaks to how browsers read the list. Since the browser is impartial, it makes the style changes as it encounters them. If the CSS says to make some HTML elements red, then later down in the CSS it says to make those elements blue, the result is blue.

      Applying styles to an element gets a little complicated, as there are many ways to tell the browser to find an element in the HTML. Each element in HTML has a set of attributes which can be used to find a specific element. Because of the cascade where the browser reads the instructions from top to bottom with impartiality, the instructions provided must be specific. This is known as specificity, where the developer must write precise criteria for the browser to find the exact element they wish to apply the styles to.

      In this tutorial you will work through multiple hands-on examples to understand the different ways styles can be applied to HTML elements and how cascade and specificity affect how styles are written.

      Prerequisites

      Using the HTML Style Attribute

      In this first step, you will apply styles to an HTML element directly with the style attribute. This method, also known as inline styling, uses an HTML element attribute to accept a CSS property as a value, and then applies it directly to the element.

      To familiarize yourself with some concepts of CSS, start by opening the index.html file in your text editor. In that file, set up the base HTML structure of the <html>, <head>, and <body> tags. Inside the <body> tags add a <div> with a short sentence of text:

      index.html

      <!doctype html>
      <html>
          <head>
              <title>Sammy Shark</title>
          </head>
          <body>
              <div>Sammy is the greatest shark in the ocean.</div>
          </body>
      </html>
      

      Next, open index.html in your browser. You will see your text in the <div> in the top left portion of the browser window. Visually, the text should appear similar to the following image with black text on a white background using serif font, such as Times New Roman:

      Text rendered in black in a serif font–the browser default style.

      To begin styling, add an attribute with an empty value to the opening <div> tag:

      index.html

      ...
      <div style="">Sammy is the greatest shark in the ocean.</div>
      ...
      

      The style attribute is a special attribute for HTML that contains CSS properties and values. The browser will apply those styles to that element.

      In this case, change the color of your sentence to navy using the color property. The format for CSS property and values begins with the property name, followed by the colon symbol :, then the property value, and finally a semicolon symbol ; after the value to tell the browser that’s all for the value:

      index.html

      ...
      <div style="color: navy;">Sammy is the greatest shark in the ocean.</div>
      ...
      

      Save index.html, return to your browser, and refresh. The text has changed from the browser default color of black to navy, as seen in the following image:

      Text rendered in navy blue with the browser default serif font.

      There are many CSS properties you can try in the style attribute, such as background-color or font-family. Typically, a browser’s default font is a serif font, such as Times New Roman. To change the font to a sans serif font, such as Arial or Helvetica, add a space after the semicolon for the color property then type the font-family property, followed by a colon, with sans-serif as the value:

      index.html

      ...
      <div style="color: navy; font-family: sans-serif;">Sammy is the greatest shark in the ocean.</div>
      ...
      

      Save your file and refresh your browser to see how the font for your sentence has changed. The font will now be the browser’s sans-serif font, such as Helvetica or Arial, instead of the default font. The following image shows how the font-family property builds on the color change to navy.

      Text rendered in navy blue with a custom sans serif font.

      Now that you have written a couple of CSS properties, wrap a word in your sentence with the <strong> element and return to your browser:

      index.html

      ...
      <div style="color: navy; font-family: sans-serif;">Sammy is the <strong>greatest</strong> shark in the ocean.</div>
      ...
      

      In your browser, the word inside the <strong> tag will appear bolder than the other words in the sentence, as shown in the following image.

      Text rendered in navy blue with a normal font weight, except the word in the <strong> tag which is bold.

      The word with the <strong> element retains the color and font-family properties of the HTML element it is inside, also known as its parent. This is an example of inheritance, where a child element, an HTML element inside another element, inherits styles that are placed on the parent element. The <strong> element also adds a browser default style of font-weight: bold;, making the text bold. Additionally, the <strong> element can have a style attribute as well to give that element a custom look:

      index.html

      ...
      <div style="color: navy; font-family: sans-serif;">Sammy is the <strong style="color: blue;">greatest</strong> shark in the ocean.</div>
      ...
      

      Save the file and refresh you browser to see the difference, as the word in the <strong> element is now blue, in contrast to the navy of the rest of the sentence. This change is shown in the following image:

      Text rendered in navy blue with a normal font weight, except the word in the <strong> tag which is bold and a lighter blue.

      In this section you used HTML style attributes to apply styles to a <div> and a <strong> element. In the next section you’ll take the styles you wrote for those specific elements and apply them to all <div> and <strong> elements on the page.

      Using the <style> Tag to Write CSS

      Next you will take what was written in the previous section and apply the styles to all similar elements on the page. You will move from using the style attribute to using the <style> HTML element. <style> is a special element that allows you to write CSS within it and have those styles applied to the whole page.

      Using the style attribute on an HTML element can be very handy, but it is limited to only that element or its descendants. To see how this works add another <div> element with a new sentence:

      index.html

      ...
      <div style="color: navy; font-family: sans-serif;">Sammy is the <strong style="color: blue;">greatest</strong> shark in the ocean.</div>
      <div>They like to swim with their friends.</div>
      ...
      

      Go to your browser and reload the page. As you may notice in the browser or the following image, the first sentence gets all the styles you wrote earlier, but the new sentence uses the browser default styles instead:

      The first sentence text is rendered with custom styles while the second sentence is rendered with browser default styles. The first sentence is a navy blue sans serif font, except for the text in the <strong> tag, which is a lighter blue and bold. The second sentence is black and a serif font.

      You could apply the same style attribute on each individual element, but that becomes very cumbersome if you have many sentences that you want to look the same. What you need is a way to target many of the same kinds of elements simultaneously. This can be done with the HTML <style> element.

      The <style> element is most often placed in the <head> tag of an HTML document. This way the browser reads the styles before reading the HTML, causing the page to load already styled. The inverse can cause a flash as the browser loads the content with browser default styles and then loads the custom styles. However, keep in mind that the <style> tag is not limited to use in the <head> and can be placed anywhere within the <body>, which can be advantageous in some scenarios.

      Add <style> tags to the <head> of your index.html file:

      index.html

      <!doctype html>
      <html>
          <head>
              <title>Sammy Shark</title>
              <style>
              </style>
          </head>
          <body>
              <div style="color: navy; font-family: sans-serif;">Sammy is the <strong style="color: blue;">greatest</strong> shark in the ocean.</div>
              <div>They like to swim with their friends.</div>
          </body>
      </html>
      

      Inside the <style> element, you can define what kind of element you want to target with selectors, which identify which HTML elements to apply styles to. Once the selector is in place, you can then group the styles you wish to apply to that element in what is called a selector block.

      To begin setting that up, look at the example from earlier. Here there is a <div> with two properties, color and font-family.

      index.html

      ...
      <div style="color: navy; font-family: sans-serif;">...</div>
      ...
      

      To target all <div> elements on the index.html page, add what is called a type selector within the <style> attribute, followed by an opening and closing curly brace, which define the selector block. This tells the browser to find all the <div> elements on the page and apply the styles found within the selector block:

      index.html

      <!doctype html>
      <html>
          <head>
              <title>Sammy Shark</title>
              <style>
                  div {
                  }
              </style>
          </head>
          <body>
              <div style="color: navy; font-family: sans-serif;">Sammy is the <strong style="color: blue;">greatest</strong> shark in the ocean.</div>
              <div>They like to swim with their friends.</div>
          </body>
      </html>
      

      Next, take the properties from the style attribute and put them inside the curly braces of the selector block. To make it easier to read, it helps to put each property on an individual line:

      index.html

      <!doctype html>
      <html>
          <head>
              <title>Sammy Shark</title>
              <style>
                  div {
                      color: navy;
                      font-family: sans-serif;
                  }
              </style>
          </head>
          <body>
              <div>Sammy is the <strong style="color: blue;">greatest</strong> shark in the ocean.</div>
              <div>They like to swim with their friends.</div>
          </body>
      </html>
      

      Once you have saved the file, return to the browser and refresh. Now both sentences have the same styles applied, all from a single selector in the <style> element:

      The text in both sentences are rendered navy blue and in a sans serif font, except for the text in the one <strong> tag, which is a lighter blue and bold.

      Add a new selector after your div selector block to apply the styles for the <strong> element in the same manner. Also, add a <strong> element around a word in your second sentence to see your new CSS on multiple elements:

      index.html

      <!doctype html>
      <html>
          <head>
              <title>Sammy Shark</title>
              <style>
                  div {
                      color: navy;
                      font-family: sans-serif;
                  }
                  strong {
                      color: blue;
                  }
              </style>
          </head>
          <body>
              <div>Sammy is the <strong>greatest</strong> shark in the ocean.</div>
              <div>They like to swim with their <strong>friends</strong>.</div>
          </body>
      </html>
      

      Save the file and refresh your browser, or look at the following image, to find that now both words using the <strong> element are the color blue:

      The text in both sentences is rendered navy blue and in a sans serif font, except for the text in both <strong> tags, which are a lighter blue and bold.

      In this section, you wrote CSS selectors within a <style> element, which applied the styles to all matching elements on the page. In the next section you will move these styles so that they can be applied on many pages of a website.

      Loading an External CSS Document into HTML

      In this section you will start working with a CSS file that is loaded on multiple HTML pages. You will move the styles from the previous section to the CSS file and create a new HTML page to see how one CSS file can style multiple pages.

      Just as the style attribute is limited to styling the single element, the CSS found in a <style> element are limited to styling a single page. Websites are most often a collection of many web pages that share the same styles. If you had multiple pages that all needed to look the same and you used the <style> element to hold your CSS, making changes to the styles would require a lot of repeat work on each page. This is where the CSS file comes in.

      Create a new file in your editor called styles.css. In that file, copy the contents of the <style> element from index.html and add them to your styles.css file. Be sure to exclude the <style> tags.

      styles.css

      div {
          color: navy;
          font-family: sans-serif;
      }
      strong {
          color: blue;
      }
      

      Now that you have an independent CSS file, it’s time to load that file on to the page so the browser can apply the styles. Start by removing the <style> tags from the <head>. Then inside the <head> tag, write a self-closing <link /> element with two attributes, href and rel. The href value contains the path to the style.css file so the browser can reference the CSS. The rel attribute should have a value of stylesheet as it defines the type of relationship between the page and the document being referenced:

      index.html

      <!doctype html>
      <html>
          <head>
              <title>Sammy Shark</title>
              <link rel="stylesheet" href="https://www.digitalocean.com/community/tutorials/styles.css" />
          </head>
          <body>
              <div>Sammy is the <strong>greatest</strong> shark in the ocean.</div>
              <div>They like to swim with their <strong>friends</strong>.</div>
          </body>
      </html>
      

      Now go to your browser and refresh index.html. In this case, you will not find anything changed since all you have done is change where the styles live.

      The text in both sentences remains rendered navy blue and in a sans serif font, except for the text in both <strong> tags, which are a lighter blue and bold.

      To demonstrate how useful a CSS file is, create a new HTML file called about.html. Copy and paste the HTML from index.html and then make changes to the sentences, or create new sentences:

      about.html

      <!doctype html>
      <html>
          <head>
              <title>About Sharks</title>
              <link rel="stylesheet" href="https://www.digitalocean.com/community/tutorials/styles.css" />
          </head>
          <body>
              <div>There are over <strong>500</strong> species of sharks.</div>
              <div>The great white shark can grow up to <strong>6.1 meters</strong> long.</div>
          </body>
      </html>
      

      Next, open about.html in a new browser window so you can view and compare both HTML files simultaneously. This results in about.html having the same styles for both div and strong elements, as shown in the following image.

      The text in both sentences on the new page are rendered navy blue and in a sans serif font, except for the text in both <strong> tags, which are a lighter blue and bold.

      Return to your text editor and open styles.css and change the div selector’s color property value to green:

      styles.css

      div {
          color: green;
          font-family: sans-serif;
      }
      strong {
          color: blue;
      }
      

      In your browser, refresh both index.html and about.html to see how changing the styles in the CSS file affects both HTML files. As the following image shows, the text changed from navy to green in both index.html and about.html:

      The text in both sentences on the about page are now rendered green and in a sans serif font, except for the text in both <strong> tags, which remains blue and bold.

      Each page has the same styles applied with the green text and blue <strong> elements, all from one central CSS file.

      In this section you created a CSS file and loaded that CSS file on multiple HTML pages. You moved your CSS from the <style> element into the CSS file, which applied the same styles to index.html and the new about.html page. Next you will start working with CSS cascade and specificity.

      Working With the Cascade and Specificity

      This section will get into the depths of the CSS features of cascade and specificity mentioned in the introduction. You will write CSS that exemplifies these concepts, starting with cascade and then specificity. Understanding cascade and specificity can help troubleshoot problems you may find in your code.

      With what you have accomplished so far, the cascade is short. As your CSS file grows in size, it is more and more necessary to be aware of the order of your CSS selectors and properties. One way to think about the cascade is to think of a water cascade and traversing rapids. It’s advisable to go with the current, as trying to go upstream will require extensive effort to make little progress. The same is true with CSS: if your code is not working as expected, it may be going against the flow of the cascade.

      To see this in practice, open up the files from earlier. Open styles.css in your text editor and index.html in your browser. The <div> elements in the browser will currently be green, with the bold text in blue. After the font-family property in the div selector, add another color property with a value of orange:

      styles.css

      div {
          color: green;
          font-family: sans-serif;
          color: orange;
      }
      strong {
          color: blue;
      }
      

      The browser traverses the cascade and hits the green style, turning the div green. Then the browser hits the orange style, and changes the color from green to orange. Refresh index.html in your browser to see the green text is now orange, as shown in the following image:

      The text in both sentences on the about page are now rendered orange and in a sans serif font, except for the text in both <strong> tags, which remains blue and bold.

      In this scenario the browser has been given two color properties, and due to the nature of the cascade, the browser applies the last color property to the element. When a property further down the cascade negates a previous property, this results in a situation called an override. As a CSS file grows in size and scope, overrides can be the source of bugs as well as the solution to problems.

      While the cascade deals with how the browser reads and applies styles to elements, specificity deals with what elements are found and styled.

      Open about.html in your browser. Right now both sentences have the same style. Next, you will change the color of the <strong> element in the second sentence to red, but keep the first <strong> color set to blue. To accomplish this change requires a higher specificity selector. Right now the selectors are what is called low specificity as they are targeting all <strong> elements on the page, regardless of their parent.

      Higher specificity can be achieved several different ways, but the most common and effective way is a class selector. On the second <strong> element, add a new attribute called class and give that attribute a property value of highlight:

      about.html

      <!doctype html>
      <html>
          <head>
              <title>About Sharks</title>
              <link rel="stylesheet" href="https://www.digitalocean.com/community/tutorials/styles.css" />
          </head>
          <body>
              <div>There are over <strong>500</strong> species of sharks.</div>
              <div>The great white shark can grow up to <strong class="highlight">6.1 meters</strong> long.</div>
          </body>
      </html>
      

      Next, open styles.css in you text editor to create a class selector. First, remove the color: orange; from the div you added earlier.

      In CSS, element selectors are written out without an identifier, but with class selectors a period (.) precedes the value found in the attribute. In this case, use the selector .hightlight to apply a color property with a value of red:

      styles.css

      div {
          color: green;
          font-family: sans-serif;
      }
      strong {
          color: blue;
      }
      .highlight {
       color: red;
      }
      

      Save the changes to both styles.css and about.html and refresh about.html in your browser. You will find that the second <strong> element is now red, as seen in the following image:

      The text in both sentences on the about page are now rendered green and in a sans serif font, except for the text in both <strong> tags, which is bold with the first <strong> text being blue and the second being red.

      To understand the robustness of specificity in regards to the cascade, swap the strong and .highlight selector blocks. Different kinds of selectors have higher specificity. In this case the class selector has a higher specificity than the element selector:

      styles.css

      div {
          color: green;
          font-family: sans-serif;
      }
      .highlight {
       color: red;
      }
      strong {
       color: blue;
      }
      

      Save and refresh about.html in your browser and you’ll notice no change. The following image shows that there is no visual change despite the reordering of the CSS.

      The text in both sentences on the about page remain rendered green and in a sans serif font, except for the text in both <strong> tags, which is bold with the first <strong> text being blue and the second being red.

      This is due to the low specificity of element selectors and the high specificity of a class selector. While the browser is reading the list from top to bottom without regard, you can tell the browser to pay more attention when applying a style by using higher specificity selectors.

      In this section you worked with the CSS features of cascade and specificity. You applied the same property twice to an element, which showed how the cascade works by using the last property in the list. You also created styles using a higher specificity selector called a class selector. Next you’ll learn about a special CSS rule that overrides both cascade and specificity.

      Using the !important Rule

      In this last section you will learn about the CSS !important rule and write an example of how to use it. This example uses a fictional scenario where you would not have control over the HTML and therefore must fix the problem only using CSS.

      Although CSS will often work with the cascade and have good specificity, there are times when a style needs to be forced. This is done by adding an !important flag at the end of a property value, before the semicolon. This is not a rule to be used lightly, and when used it is a good practice to include a code comment explaining the reason for using !important.

      Warning: Due to how the !important rule works, it should be used only if all other methods fail. Using the rule overrides the value on all matching elements, which makes it difficult or impossible to override further. This will make your code less legible to other developers.

      To see how this works, open up index.html in your editor and add a style attribute with a color set to red:

      index.html

      <!doctype html>
      <html>
          <head>
              <title>Sammy Shark</title>
              <link href="https://www.digitalocean.com/community/tutorials/styles.css" rel="stylesheet" />
          </head>
          <body>
              <div>Sammy is the <strong style="color: red;">greatest</strong> shark in the ocean.</div>
              <div>They like to swim with their friends.</div>
          </body>
      </html>
      

      Load index.html in your browser and you will find that the style attribute overrides the blue color with red, since a style attribute has higher specificity than the CSS selector. What is in the browser will look similar to the following image:

      The text in the sentence is green with sans serif, except for the text in the <strong> tag, which is red and bold.

      When working with websites it is common to have Javascript loaded that may apply inline styles like this. Elements with style attributes are at the bottom of the cascade, meaning that even with styles that turn all strong tags blue, this one will be red. In a scenario where Javascript creates the style attribute, it cannot be removed from the HTML.

      To force a style override, open up styles.css in your editor and after the blue property value in your strong selector, add !important:

      styles.css

      ...
      strong {
          color: blue !important;
      }
      

      Now return to your browser and refresh index.html. You will see the blue color again, as in the following image:

      The text in the sentence is green with sans serif font, except for the text in the <strong> tag, which is blue and bold.

      Despite the style attribute defining the color as red it is now blue, thanks to the !important rule telling the browser that this is the more important style to use. It is helpful to add a CSS code comment explaining the reason for the !important so future developers or future you understand why you are using it.

      styles.css

      ...
      strong {
          /* !imporant used here because of JavaScript applying a style attribute on the selector */
          color: blue !important;
      }
      

      In this section you learned about the !important rule and used it in a real-world scenario. You also learned that that the !important rule is a dangerous tool that should be used intentionally because of how drastic it overrides cascade and specificity. Additionally, you wrote a CSS comment, which is used to inform future developers looking at your code as well as a reminder to you when you return to your code later.

      Conclusion

      CSS is a versatile language made for manipulating and styling HTML. In this tutorial you styled HTML elements through various methods of applying styles. You now have the foundation to begin writing your own styles. If you want to dive further into understanding CSS and how it works, the World Wide Web Consortium (W3C), the governing body for CSS, provides all kinds of information about the language.

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



      Source link

      Understanding This, Bind, Call, and Apply in JavaScript


      The author selected the Open Internet/Free Speech Fund to receive a donation as part of the Write for DOnations program.

      The this keyword is a very important concept in JavaScript, and also a particularly confusing one to both new developers and those who have experience in other programming languages. In JavaScript, this is a reference to an object. The object that this refers to can vary, implicitly based on whether it is global, on an object, or in a constructor, and can also vary explicitly based on usage of the Function prototype methods bind, call, and apply.

      Although this is a bit of a complex topic, it is also one that appears as soon as you begin writing your first JavaScript programs. Whether you’re trying to access an element or event in the Document Object Model (DOM), building classes for writing in the object-oriented programming style, or using the properties and methods of regular objects, you will encounter this.

      In this article, you’ll learn what this refers to implicitly based on context, and you’ll learn how to use the bind, call, and apply methods to explicitly determine the value of this.

      Implicit Context

      There are four main contexts in which the value of this can be implicitly inferred:

      • the global context
      • as a method within an object
      • as a constructor on a function or class
      • as a DOM event handler

      Global

      In the global context, this refers to the global object. When you’re working in a browser, the global context is would be window. When you’re working in Node.js, the global context is global.

      Note: If you are not yet familiar with the concept of scope in JavaScript, please review Understanding Variables, Scope, and Hoisting in JavaScript.

      For the examples, you will practice the code in the browser’s Developer Tools console. Read How to Use the JavaScript Developer Console if you are not familiar with running JavaScript code in the browser.

      If you log the value of this without any other code, you will see what object this refers to.

      console.log(this)
      

      Output

      Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}

      You can see that this is window, which is the global object of a browser.

      In Understanding Variables, Scope, and Hoisting in JavaScript, you learned that functions have their own context for variables. You might be tempted to think that this would follow the same rules inside a function, but it does not. A top-level function will still retain the this reference of the global object.

      You write a top-level function, or a function that is not associated with any object, like this:

      function printThis() {
        console.log(this)
      }
      
      printThis()
      

      Output

      Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}

      Even within a function, this still refers to the window, or global object.

      However, when using strict mode, the context of this within a function on the global context will be undefined.

      'use strict'
      
      function printThis() {
        console.log(this)
      }
      
      printThis()
      

      Output

      undefined

      Generally, it is safer to use strict mode to reduce the probability of this having an unexpected scope. Rarely will someone want to refer to the window object using this.

      For more information about strict mode and what changes it makes regarding mistakes and security, read the Strict mode documentation on MDN.

      An Object Method

      A method is a function on an object, or a task that an object can perform. A method uses this to refer to the properties of the object.

      const america = {
        name: 'The United States of America',
        yearFounded: 1776,
      
        describe() {
          console.log(`${this.name} was founded in ${this.yearFounded}.`)
        },
      }
      
      america.describe()
      

      Output

      "The United States of America was founded in 1776."

      In this example, this is the same as america.

      In a nested object, this refers to the current object scope of the method. In the following example, this.symbol within the details object refers to details.symbol.

      const america = {
        name: 'The United States of America',
        yearFounded: 1776,
        details: {
          symbol: 'eagle',
          currency: 'USD',
          printDetails() {
            console.log(`The symbol is the ${this.symbol} and the currency is ${this.currency}.`)
          },
        },
      }
      
      america.details.printDetails()
      

      Output

      "The symbol is the eagle and the currency is USD."

      Another way of thinking about it is that this refers to the object on the left side of the dot when calling a method.

      A Function Constructor

      When you use the new keyword, it creates an instance of a constructor function or class. Function constructors were the standard way to initialize a user-defined object before the class syntax was introduced in the ECMAScript 2015 update to JavaScript. In Understanding Classes in JavaScript, you will learn how to create a function constructor and an equivalent class constructor.

      function Country(name, yearFounded) {
        this.name = name
        this.yearFounded = yearFounded
      
        this.describe = function() {
          console.log(`${this.name} was founded in ${this.yearFounded}.`)
        }
      }
      
      const america = new Country('The United States of America', 1776)
      
      america.describe()
      

      Output

      "The United States of America was founded in 1776."

      In this context, this is now bound to the instance of Country, which is contained in the america constant.

      A Class Constructor

      A constructor on a class acts the same as a constructor on a function. Read more about the similarities and differences between function constructors and ES6 classes in Understanding Classes in JavaScript.

      class Country {
        constructor(name, yearFounded) {
          this.name = name
          this.yearFounded = yearFounded
        }
      
        describe() {
          console.log(`${this.name} was founded in ${this.yearFounded}.`)
        }
      }
      
      const america = new Country('The United States of America', 1776)
      
      america.describe()
      

      this in the describe method refers to the instance of Country, which is america.

      Output

      "The United States of America was founded in 1776."

      A DOM Event Handler

      In the browser, there is a special this context for event handlers. In an event handler called by addEventListener, this will refer to event.currentTarget. More often than not, developers will simply use event.target or event.currentTarget as needed to access elements in the DOM, but since the this reference changes in this context, it is important to know.

      In the following example, we’ll create a button, add text to it, and append it to the DOM. When we log the value of this within the event handler, it will print the target.

      const button = document.createElement('button')
      button.textContent = 'Click me'
      document.body.append(button)
      
      button.addEventListener('click', function(event) {
        console.log(this)
      })
      

      Output

      <button>Click me</button>

      Once you paste this into your browser, you will see a button appended to the page that says “Click me”. If you click the button, you will see <button>Click me</button> appear in your console, as clicking the button logs the element, which is the button itself. Therefore, as you can see, this refers to the targeted element, which is the element we added an event listener to.

      Explicit Context

      In all of the previous examples, the value of this was determined by its context—whether it is global, in an object, in a constructed function or class, or on a DOM event handler. However, using call, apply, or bind, you can explicitly determine what this should refer to.

      It is difficult to define exactly when to use call, apply, or bind, as it will depend on the context of your program. bind can be particularly helpful when you want to use events to access properties of one class within another class. For example, if you were to write a simple game, you might separate the user interface and I/O into one class, and the game logic and state into another. Since the game logic would need to access input, such as key press and click, you would want to bind the events to access the this value of the game logic class.

      The important part is to know how to determine what object this refers to, which you can do implicitly with what you learned in the previous sections, or explicitly with the three methods you will learn next.

      Call and Apply

      call and apply are very similar—they invoke a function with a specified this context, and optional arguments. The only difference between call and apply is that call requires the arguments to be passed in one-by-one, and apply takes the arguments as an array.

      In this example, we’ll create an object, and create a function that references this but has no this context.

      const book = {
        title: 'Brave New World',
        author: 'Aldous Huxley',
      }
      
      function summary() {
        console.log(`${this.title} was written by ${this.author}.`)
      }
      
      summary()
      

      Output

      "undefined was written by undefined"

      Since summary and book have no connection, invoking summary by itself will only print undefined, as it’s looking for those properties on the global object.

      Note: Attempting this in strict mode would result in Uncaught TypeError: Cannot read property 'title' of undefined, as this itself would be undefined.

      However, you can use call and apply to invoke the this context of book on the function.

      summary.call(book)
      // or:
      summary.apply(book)
      

      Output

      "Brave New World was written by Aldous Huxley."

      There is now a connection between book and summary when these methods are applied. Let’s confirm exactly what this is.

      function printThis() {
        console.log(this)
      }
      
      printThis.call(book)
      // or:
      whatIsThis.apply(book)
      

      Output

      {title: "Brave New World", author: "Aldous Huxley"}

      In this case, this actually becomes the object passed as an argument.

      This is how call and apply are the same, but there is one small difference. In addition to being able to pass the this context as the first argument, you can also pass additional arguments through.

      function longerSummary(genre, year) {
        console.log(
          `${this.title} was written by ${this.author}. It is a ${genre} novel written in ${year}.`
        )
      }
      

      With call each additional value you want to pass is sent as an additional argument.

      longerSummary.call(book, 'dystopian', 1932)
      

      Output

      "Brave New World was written by Aldous Huxley. It is a dystopian novel written in 1932."

      If you try to send the exact same arguments with apply, this is what happens:

      longerSummary.apply(book, 'dystopian', 1932)
      

      Output

      Uncaught TypeError: CreateListFromArrayLike called on non-object at <anonymous>:1:15

      Instead, for apply, you have to pass all the arguments in an array.

      longerSummary.apply(book, ['dystopian', 1932])
      

      Output

      "Brave New World was written by Aldous Huxley. It is a dystopian novel written in 1932."

      The difference between passing the arguments individually or in an array is subtle, but it’s important to be aware of. It might be simpler and more convenient to use apply, as it would not require changing the function call if some parameter details changed.

      Bind

      Both call and apply are one-time use methods—if you call the method with the this context it will have it, but the original function will remain unchanged.

      Sometimes, you might need to use a method over and over with the this context of another object, and in that case you could use the bind method to create a brand new function with an explicitly bound this.

      const braveNewWorldSummary = summary.bind(book)
      
      braveNewWorldSummary()
      

      Output

      "Brave New World was written by Aldous Huxley"

      In this example, every time you call braveNewWorldSummary, it will always return the original this value bound to it. Attempting to bind a new this context to it will fail, so you can always trust a bound function to return the this value you expect.

      const braveNewWorldSummary = summary.bind(book)
      
      braveNewWorldSummary() // Brave New World was written by Aldous Huxley.
      
      const book2 = {
        title: '1984',
        author: 'George Orwell',
      }
      
      braveNewWorldSummary.bind(book2)
      
      braveNewWorldSummary() // Brave New World was written by Aldous Huxley.
      

      Although this example tries to bind braveNewWorldSummary once again, it retains the original this context from the first time it was bound.

      Arrow Functions

      Arrow functions do not have their own this binding. Instead, they go up to the next level of execution.

      const whoAmI = {
        name: 'Leslie Knope',
        regularFunction: function() {
          console.log(this.name)
        },
        arrowFunction: () => {
          console.log(this.name)
        },
      }
      
      whoAmI.regularFunction() // "Leslie Knope"
      whoAmI.arrowFunction() // undefined
      

      It can be useful to use the arrow function in cases where you really want this to refer to the outer context. For example, if you had an event listener inside of a class, you would probably want this to refer to some value in the class.

      In this example, you’ll create and append button to the DOM like before, but the class will have an event listener that will change the text value of the button when clicked.

      const button = document.createElement('button')
      button.textContent = 'Click me'
      document.body.append(button)
      
      class Display {
        constructor() {
          this.buttonText = 'New text'
      
          button.addEventListener('click', event => {
            event.target.textContent = this.buttonText
          })
        }
      }
      
      new Display()
      

      If you click the button, the text content will change to the value of buttonText. If you hadn’t used an arrow function here, this would be equal to event.currentTarget, and you wouldn’t be able to use it to access a value within the class without explicitly binding it. This tactic is often used on class methods in frameworks like React.

      Conclusion

      In this article, you learned about this in JavaScript, and the many different values it might have based on implicit runtime binding, and explicit binding through bind, call, and apply. You also learned about how the lack of this binding in arrow functions can be used to refer to a different context. With this knowledge, you should be able to determine the value of this in your programs.



      Source link