One place for hosting & domains

      CSS

      How To Use Relationships to Select 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

      Selectors are what web browsers use to find and apply specific styles to an element via CSS. You can apply these styles broadly with type selectors that select many elements of the same kind. In addition to targeting specific attributes of an element like id or class, it is possible to select an element based on its relationship or proximity to another element. For example, you can select an HTML element that follows a preceding element or the first element in a series.

      In this tutorial, you will use several CSS-relationship-based approaches to select and style elements on an HTML page. You will create a page of content with different styling scenarios for each relationship selector. You will use the descendant combinator, child combinator, general sibling combinator, and adjacent sibling combinator, as well as the first-, last-, only-, and nth-child pseudo-class selectors. These selectors apply styles based on the relative conditions of surrounding elements, as opposed to the direct method of traditional selectors.

      Prerequisites

      Setting Up the Initial HTML and CSS

      To start, you will set up the HTML and CSS code that you will work on throughout the rest of the tutorial.

      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. Then set the title of the page, add a <meta> tag defining how mobile devices should render the page, and finally load the CSS file 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>Relationship Selectors</title>
          <link rel="stylesheet" href="https://www.digitalocean.com/community/tutorials/styles.css">
        </head>
        <body>
        </body>
      </html>
      

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

      index.html

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

      Be sure to save these additions to index.html. The <h1> element displays the title of the page. The <main> element with a class attribute of content-width will contain the contents of the page, which you will add throughout the tutorial.

      Next, create a new file called styles.css in the same directory as your index.html file, then open the new file in your text editor. This file will load the styles that the browser will then apply to the content of index.html. Add the following CSS code to your styles.css file:

      styles.css

      body {
        font-family: system-ui, sans-serif;
        color: #333;
      }
      
      .content-width {
        width: 90%;
        margin: 2rem auto;
        max-width: 70ch; 
      }
      
      section{
        margin: 4rem 0;
      }
      
      h1 {
        text-align: center;
      }
      
      h2 {
        color: mediumblue;
      }
      

      In this code, the body type selector defines new defaults for the font-family and color values on the page. The .content-width class selector is set up to be 90% of the page’s width and to grow to a maximum width of 70 character widths of the current font-size. 70 characters is the ideal maximum length of a line of text. The margin on the .content-width property keeps space above and below the element and keeps the container horizontally centered. There will be several <section> elements on this page, so the section type selector applies a margin to give ample space between each grouping. Lastly, the h1 and h2 type selectors set the <h1> content to be centered and the <h2> content to have a color of mediumblue.

      In this section you, set up the starting points for your HTML and CSS files. In the next section, you will add some more content to index.html, then use the descendant combinator to apply styles with CSS.

      Descendant Combinators

      When working with relationship-based selectors, you will come across familial terminology, such as parent, child, ancestor, and in this case, descendant. The descendant combinator is a space-separated list of selectors that matches the HTML structure in order to apply styles to elements that have a particular ancestor. The last selector in the list is the one that receives the styles, and is the descendant of the previous selectors in the list.

      The descendant combinator is the quickest way to scope a style. Scoping is the method of providing additional details to increase the specificity of a selector. The descendant combinator aids scoping by prepending the selector with an ancestor selector. For example, the a type selector will get all the <a> tags on a page, but the header a descendant selector will select only the <a> tags inside of a <header> element.

      To begin using the descendant combinator, open index.html in your text editor. Create a <section> element with a class attribute of descendant. Inside the <section> element, add an <h2> element containing Descendant Combinator Selector, then add two <p> elements and fill them with content from Cupcake Ipsum. Wrap the second <p> element in a <blockquote>. The highlighted HTML in the following code block demonstrates how this will be set up:

      index.html

      ...
      <main class="content-width">
        <section class="descendant">
          <h2>Descendant Combinator Selector</h2>
          <p>Sweet roll pudding ice cream jelly beans caramels cookie caramels. Macaroon cheesecake cookie marzipan icing jujubes. Chocolate bar jelly-o wafer toffee cookie muffin soufflé lemon drops bonbon. Soufflé danish gingerbread sweet roll marzipan carrot cake.</p>
      
          <blockquote>
            <p>Bear claw pastry tootsie roll biscuit jujubes oat cake toffee wafer lemon drops. Croissant pie lemon drops cake chupa chups chocolate bar chupa chups marshmallow. Cake pudding icing tiramisu tiramisu pastry topping. Gingerbread shortbread lollipop chocolate bar icing.</p>
          </blockquote>
        </section>
      </main>
      ...
      

      Save your changes to index.html then open styles.css in your text editor. Add a .descendant class selector followed by a space, then a blockquote type selector. This will create a selector that only applies styles to a blockquote element that is inside an element with a class attribute containing descendant. The highlighted CSS in the following code block demonstrates this selector with styles for the blockquote element:

      styles.css

      ...
      h2 {
        color: mediumblue;
      }
      
      .descendant blockquote {
        margin: 2rem 0;
        padding: 1rem 1rem 1rem 2rem;
        border-left: 0.125rem indigo solid;
        background-color: lavender;
      }
      

      Save your changes to styles.css and open index.html in your browser. The properties used on this blockquote element provide additional spacing above and below with the margin property. Then, the padding property gives the content space inside the container. Lastly, the container is visually defined by a combination of the border-left property creating a solid indigo line and a lavender backdrop applied with the background-color property. The following screenshot shows how this code will render in the browser:

      Large bold blue headline followed by a smaller paragraph of black text. Below the paragraph is a light purple box with a darker purple border on the left side. Inside the box is another paragraph of black text.

      You can also apply descendant combinator selectors to a descendant element regardless of how deep in the HTML that element is relative to the ancestor selector. Similar to how the previous code set styles to the <blockquote> element inside of the .descendant class selector, you will next apply styles to all <p> elements, regardless of the element they are contained in.

      Return to your styles.css file in your text editor. Then, add a new descendant combinator selector for a p element selector with an ancestor of .descendant. Inside the selector block, set the line-height property to a value of 1.5. The highlighted CSS in the following code block shows how this will look:

      styles.css

      ...
      .descendant blockquote {
        margin: 2rem 0;
        padding: 1rem 1rem 1rem 2rem;
        border-left: 0.125rem indigo solid;
        background-color: lavender;
      }
      
      .descendant p {
        line-height: 1.5;
      }
      

      Save your changes to styles.css and open index.html in your browser. The lines of text for both <p> elements are now larger, despite one of those <p> elements being inside the <blockquote> element. The following image illustrates how this will render in the browser:

      Large bold blue headline followed by a paragraph of black text with a more legible line height. Below the paragraph is a light purple box with a darker purple border on the left side. Inside the box is another paragraph of black text with similar line height as the previous paragraph.

      Finally, return to your styles.css file in your text editor. You will create a new descendant selector to apply styles directly to the <p> element inside the <blockquote> element. Start by writing out .descendant blockquote p, which will tell the browser to find the <p> elements on the page that is somewhere inside a <blockquote> element, which in turn is inside an element with a class attribute of descendant. Then in the selector block, add a font-size property set to 1.25rem and a color property with #222 as the value. The highlighted CSS in the following code block demonstrates the necessary structure:

      styles.css

      ...
      .descendant p {
        line-height: 1.5;
      }
      
      .descendant blockquote p {
        font-size: 1.25rem;
        color: #222;
      }
      

      Save your changes to styles.css and open index.html in your browser. The font-size of the <p> element’s content inside the <blockquote> will now be much larger and have a slightly softer gray color, as shown in the following image:

      Large bold blue headline followed by a smaller paragraph of black text. Below the paragraph is a light purple box with a darker purple border on the left side. Inside the box is another paragraph of larger black text.

      In this section, you used the descendant combinator selector to scope styles to elements that are found inside of another element to apply styles. In the next section, you will use the child combinator selector to select only the first-level children of an element.

      Child Combinator Selectors

      When scoping styles, there are times that you don’t want all elements within an ancestor selector, just those immediately inside the element. For example, you might want to style all the top-level links in a navigation bar, and not any links that are contained in any sub navigation elements. For these moments when only the children of a given parent need to be styled, you can use the child combinator selector.

      Before working with this new selector, return to index.html in your text editor and add the highlighted HTML from the following code block inside the <main> element and after the previous <section> element:

      index.html

      ...
      <main class="content-width">
        ...
        <section class="child">
          <h2>Child Combinator Selector</h2>
      
          <p>Sweet roll carrot cake cake chocolate bar sugar plum. Cheesecake caramels jelly-o sugar plum icing muffin marzipan chocolate bar jujubes. Dessert cotton candy gummies chocolate cake sweet.</p>
      
          <div>
            <p>Liquorice sesame snaps chocolate bar soufflé oat cake candy canes fruitcake lollipop candy. Macaroon wafer cotton candy tootsie roll jelly halvah. Icing powder soufflé toffee dessert gummies bear claw donut cake.</p>
          </div>
        </section>
      </main>
      ...
      

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

      First, you will extend the .descendant p selector with a line-height property to include the <p> elements found inside the <section> with the child class. You will accomplish by using a general combinator, which allows multiple selectors to share the same styles. A comma is needed between each selector to apply the styles. Add a comma after the .descendant p selector, then add a .child p descendant combinator, as demonstrated in the following highlighted code:

      styles.css

      ...
      .descendant p,
      .child p {
        line-height: 1.5;
      }
      ...
      

      Save your changes to styles.css and open index.html in your browser. The content in the new section will now have a larger space between each line of text. The following image depicts how this will appear in the browser:

      Large bold blue headline followed by two smaller sized black text paragraphs.

      Next, to select only the <p> element, which is the direct child of the <section class="child"> element, you will use the child combinator selector. This is constructed by writing the parent selector followed by the greater-than sign (>) and then the child selector.

      Return to styles.css in your text editor and go to the end of the file. Create a child combinator selector by setting the parent selector as .child and the child selector as p. Then inside the selector block set the color property to a named value of forestgreen. The highlighted CSS in the following code block shows how this is written:

      styles.css

      ...
      .descendant blockquote p {
        font-size: 1.25rem;
        color: #222;
      }
      
      .child > p {
        color: forestgreen;
      }
      

      Save your changes to styles.css and open index.html in your browser. Only the first <p> element has text set to the forestgreen color. The <div> element wrapping the second <p> element changes the relationship to the <section> element from a child to a grandchild. Because of this, that <p> element is invalid for the child combinator selector. The following image illustrates how this is rendered in the browser:

      Large bold blue headline followed by a smaller sized green text paragraph then a similar sized black text paragraph.

      In this section, you used the child combinator selector to select and apply styles to the immediate children of a parent element. In the next section, you will work with relationships of sibling elements to apply styles to elements when they have a common parent.

      Sibling Combinator Selectors

      The general sibling combinator provides a way to scope styling to elements that come after a specific element and have the same parent element, but which may not be next to each other. Often this will occur when the HTML is generally known but not predictable, such as dynamically generated content.

      First, you will need HTML siblings to use the selector. Return to index.html in your text editor. Then, add the highlighted HTML from the following code block before the closing </main> tag:

      index.html

      ...
      <main class="content-width">
        ...
        <section class="general-sibling">
          <h2>General Sibling Combinator Selector</h2>
      
          <p>Donut dessert jelly-o pie gingerbread jelly-o gummies biscuit gummies. Fruitcake jelly bonbon croissant carrot cake gummies. Candy canes apple pie liquorice gummi bears shortbread lemon drops jelly-o marzipan halvah. Jujubes chocolate bar tart bear claw sweet.</p>
      
          <div>
            <p>Carrot cake soufflé oat cake gummies marzipan sugar plum pastry jujubes. Tootsie roll pastry danish cake cake cake jelly sesame snaps. Donut pastry brownie brownie pie croissant</p>
          </div>
      
          <p>Gummies apple pie gingerbread cheesecake chupa chups cookie jelly beans. Tootsie roll dessert liquorice jujubes apple pie biscuit gummies biscuit jelly-o. Cake candy canes danish sugar plum biscuit lemon drops icing.</p>
      
          <p>Jelly beans candy candy cookie cotton candy. Liquorice gummies biscuit dragée sesame snaps oat cake tiramisu. Powder sweet dessert chupa chups ice cream sweet.</p>
        </section>
      </main>
      ...
      

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

      Next, you will extend the grouping selector with a line-height property to include the <p> elements found inside the <section> with the general-sibling class. Again, this is accomplished by adding a comma after the .child p selector and adding a .general-sibling p descendant combinator, as shown in the following highlighted CSS:

      styles.css

      ...
      .descendant p,
      .child p,
      .general-sibling p {
        line-height: 1.5;
      }
      ...
      

      Save your changes to styles.css and refresh index.html in your browser. The content in the new section will now have a larger space between each line of text. The following image depicts how this will appear in the browser:

      Large bold blue headline followed by four smaller-sized black text paragraphs.

      Next, you will write the styles for the sibling <p> elements that come after another <p> element of the same parent. This is done by writing a selector, followed by a tilde (~), followed by the selector of the sibling you wish to style.

      Return to styles.css in your text editor and add a new selector for .general-sibling p. This will find the <p> elements with a parent that has a class attribute with general-sibling. Then add the tilde symbol followed by a p element selector. Inside the selector block, set the color property to the named value of lightseagreen, as shown in the highlighted CSS of the following code block:

      styles.css

      ...
      .child > p {
        color: forestgreen;
      }
      
      .general-sibling p ~ p {
        color: lightseagreen;
      }
      

      Save your changes to styles.css and return to your browser to refresh index.html. The following image showcases how this code will render in the browser:

      Large bold blue headline followed by two smaller-sized black text paragraphs then two similar-sized teal text paragraphs.

      Only the last two of the four paragraphs will have the lightseagreen color. This is because the first paragraph is the initializing selector, the .general-sibling p part of the combinator, meaning the subsequent <p> elements will receive the styling. The second paragraph of text is inside a <p> element, but because it is nested inside a <div> element it is no longer a sibling of the initializing selector.

      Sibling selectors do not have to be of the same element type. To demonstrate this, return to the styles.css file in your text editor and change the first p in the selector to a div instead, as highlighted in the following code block:

      styles.css

      ...
      .general-sibling div ~ p {
        color: lightseagreen;
      }
      

      Save that small change to styles.css and refresh index.html in your browser. Visually nothing changed, but the way the styles are applied by the browser did change. The elements receiving the styles must be <p> elements that are sibling subsequents to the selector before the tilde. Since the order of the HTML is <p />, <div />, <p />, then <p />, the results of both general sibling selectors are the same. The first <p> element does not receive the styles because, though it is a sibling, it comes before the initializing .general-sibling div selector.

      In this section, you used the general sibling combinator to apply styles to any sibling elements of a certain kind. In the next section, you will use the adjacent sibling combinator to apply styles to the sibling immediately after an element.

      Adjacent Sibling Combinator Selectors

      If you only need to apply a style when two particular elements are next to each other in the HTML, the adjacent sibling combinator will help select the appropriate element. This can be useful when applying additional space between a heading text and a body text, or to add a divider between elements.

      To start working with the adjacent sibling combinator, first open index.html in your text editor. Then, inside the <main> element, add the highlighted HTML from the following code block:

      index.html

      ...
      <main class="content-width">
        ...
        <section class="adjacent-sibling">
          <h2>Adjacent Sibling Combinator Selector</h2>
      
          <p>Donut dessert jelly-o pie gingerbread jelly-o gummies biscuit gummies. Fruitcake jelly bonbon croissant carrot cake gummies. Candy canes apple pie liquorice gummi bears shortbread lemon drops jelly-o marzipan halvah. Jujubes chocolate bar tart bear claw sweet.</p>
      
          <div>
            <p>Carrot cake soufflé oat cake gummies marzipan sugar plum pastry jujubes. Tootsie roll pastry danish cake cake cake jelly sesame snaps. Donut pastry brownie brownie pie croissant</p>
          </div>
      
          <p>Gummies apple pie gingerbread cheesecake chupa chups cookie jelly beans. Tootsie roll dessert liquorice jujubes apple pie biscuit gummies biscuit jelly-o. Cake candy canes danish sugar plum biscuit lemon drops icing.</p>
      
          <p>Jelly beans candy candy cookie cotton candy. Liquorice gummies biscuit dragée sesame snaps oat cake tiramisu. Powder sweet dessert chupa chups ice cream sweet.</p>
        </section>
      </main>
      

      Save your changes to index.html, then open styles.css in your text editor. Extend the selector grouping of the line-height with .adjacent-sibling p, as highlighted in the following code block:

      styles.css

      ...
      .descendant p,
      .child p,
      .general-sibling p,
      .adjacent-sibling p {
        line-height: 1.5;
      }
      ...
      

      Next, go to the last line of the styles.css file. Here, you will write an adjacent sibling combinator selector to apply a top border and extra padding to a <p> element that is preceded by another <p> element. The highlighted CSS in the following code block displays how this is written:

      styles.css

      ...
      .general-sibling div ~ p {
        color: lightseagreen;
      }
      
      .adjacent-sibling p + p {
        border-top: 1px solid black;
        padding-top: 1em;
      }
      

      Since this style should only be applied to a <p> element inside the <section class="adjacent-sibling"> element, the first selector must use a descendant combinator. The second element in the selector only needs to use an element selector, since that is the adjacent element to the sibling.

      Note: It is important to remember when working with the sibling selectors that the last selector in the sequence is the element that is selected. Let’s say an adjacent sibling combinator was written as .adjacent-sibling p + .adjacent-sibling p. The intent of this code may be to select the <p> after a <p> inside an ancestor of .adjacent-sibling. But instead, this adjacent sibling selector will try to target the <p> inside an ancestor of .adjacent-sibling that comes immediately after a <p> sibling, which in turn is a descendant of another element with a class of adjacent-sibling.

      Save your changes to styles.css and refresh index.html in your browser. The border will be rendered above the last paragraph, since this is where a <p> is next to a <p>. The extra padding on top visually compensates for the margin so there is equal spacing above and below the line, as shown in the following image:

      Large bold blue headline followed by four smaller-sized black text paragraphs with a thin black rule line between the third and fourth paragraphs.

      This selector is not limited to like siblings; it can be a sibling selector of any kind. Return to styles.css and create a new adjacent sibling selector to add a red border between the <div> element and the adjacent <p> element, along with some extra top padding. The highlighted CSS in the following code block demonstrates how this will be set up:

      styles.css

      ...
      .adjacent-sibling p + p {
        border-top: 1px solid black;
        padding-top: 1em;
      }
      
      .adjacent-sibling div + p {
        border-top: 1px solid red;
        padding-top: 1em;
      }
      

      Save your changes to styles.css and open index.html in your browser. There is now a red line between the second and third paragraphs, since this is where a <div> element is next to a <p> element. The following image shows how this will be rendered in the browser:

      Large bold blue headline followed by four smaller-sized black text paragraphs with a thin red rule line after the second paragraph and a thin black rule line between the third and fourth paragraphs.

      In this section, you used the adjacent sibling combinator to apply styles to the element immediately following a sibling element. In the next section, you will use the first child pseudo-class to apply styles to the first element of a parent.

      first-child Pseudo-Class Selector

      When it comes to working with specific child elements, CSS provides pseudo-class selectors to refine the selection process. A pseudo-class selector is a state related to the condition of the selector. In this section, you will target elements that are the first child, meaning the first nested element, of a specified or unspecified parent element.

      To begin, open index.html in your text editor. Then, inside the <main> element, add the highlighted HTML from the following code block:

      index.html

      ...
      <main class="content-width">
        ...
        <section>
          <h2>First and Last Child Pseudo-Class Selector</h2>
          <ul>
            <li>Sugar plum gingerbread</li>
            <li>Sesame snaps sweet ice cream</li>
            <li>Jelly beans macaroon dessert</li>
            <li>Chocolate cheesecake</li>
            <li>Sweet roll pastry carrot cake</li>
            <li>Sugar plum tart cake</li>
            <li>Pudding soufflé</li>
            <li>Marshmallow oat cake</li>
          </ul>
        </section>
      </main>
      

      This HTML creates an unordered list, as defined by the <ul> element, with eight list items (<li>) nested inside. This will create a bulleted list of content by default in the browser.

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

      In your CSS file, add a ul element selector. This section will not require any class-related scoping. Then inside the selector block add the property list-style with a value of none, which will remove the bulleted list styling. Set the margin property to 1rem 0 and the padding property to 0, which will override the browser default styles. The highlighted CSS in the following code block demonstrates how to set this up:

      styles.css

      ...
      .adjacent-sibling div + p {
        border-top: 1px solid red;
        padding-top: 1em;
      }
      
      ul {
        list-style: none;
        margin: 1rem 0;
        padding: 0;
      }
      

      Save your changes to styles.css and open index.html in your browser. The unordered list will no longer have bullets and will be aligned with the heading text, as shown in the following image:

      Large bold blue headline followed by an unordered list of eight items.

      Next, to provide some default styling to the list items, create a li element selector. Apply a padding property in the selector block with a value of 0.5rem 0.75rem. Then, add a light green background-color property with hsl(120, 50%, 95%) as the value. Lastly, add a border property set to 1px and solid with a slightly darker green color using hsl(120, 50%, 80%), as highlighted in the following code block:

      styles.css

      ...
      ul {
        list-style: none;
        margin: 1rem 0;
        padding: 0;
      }
      
      ul li {
        padding: 0.5rem 0.75rem;
        background-color: hsl(120, 50%, 95%);
        border: 1px solid hsl(120, 50%, 80%);
      }
      

      Save these changes to styles.css and open index.html in your browser. Each list item now has a light green background color with a darker green border, with text inset by the padding property. The following image shows how this will render in the browser:

      Large bold blue headline followed by an unordered list of eight items each in a light green box with a green border.

      The top and bottom borders of the list items double up the thickness of the border between items, making the border thickness inconsistent. To address this situation, return to styles.css in your text editor. Then, add a new adjacent sibling combinator to select an <li> element that comes after an <li> element inside a <ul> element, as depicted in the following code block:

      styles.css

      ...
      ul li {
        padding: 0.5rem 0.75rem;
        background-color: hsl(120, 50%, 95%);
        border: 1px solid hsl(120, 50%, 80%);
      }
      
      ul li + li {
        border-top: none;
      }
      

      Save that addition to styles.css and refresh index.html in your browser. The extra thick line between list items has been addressed by removing the border from the top of any list item that comes after another list item. The following image showcases how this will appear in the browser:

      Large bold blue headline followed by an unordered list of eight items each in a light green box with a green border.

      Now, return to styles.css to apply rounded corners to the top of the first list item. Since this needs to apply to only the first list item of an unordered list, you can use the child combinator selector. This will ensure that only the first direct child of the unordered list is selected. After the li element selector, append :first-child immediately without a space. For the rounded corner style on the top use the border-radius property with the value set to 0.75rem 0.75rem 0 0, which will add the rounded corners to the top left and top right corners. The highlighted CSS in the following code block shows how this is written:

      styles.css

      ...
      ul li + li {
        border-top: none;
      }
      
      ul > li:first-child {
        border-radius: 0.75rem 0.75rem 0 0;
      }
      

      Save this change to styles.css and return to the browser to refresh index.html. The first item in the unordered list now has rounded corners on the top side of the element. The following image illustrates how this is rendered in the browser:

      Large bold blue headline followed by an unordered list of eight items each in a light green box with a green border. The first item in the list has rounded corners.

      In this section, you created styles for a list and applied rounded corners to the first child <li> element of the <ul> parent element. In the next section, you will style the <li> at the end of the list with the last-child pseudo-class selector.

      last-child Pseudo-Class Selector

      In the same way that the first-child pseudo-class selector captures the first element of a parent, the last-child pseudo-class selector captures the last element of a parent element. In the previous section, you added rounded corners to the top of the first list item. In this section, you will add rounded corners to the bottom of the last item.

      To begin, return to styles.css in your text editor. After the selector block for the :first-child, add a similarly formatted child combinator with a :last-child on the li element selector. In the selector block, add a border-radius property and then for the value use 0 0 0.75rem 0.75rem. This value will set the top values to 0 and the bottom right and bottom left curve values to 0.75rem. The highlighted CSS in the following code block show how this is composed:

      styles.css

      ...
      ul > li:first-child {
        border-radius: 0.75rem 0.75rem 0 0;
      }
      
      ul > li:last-child {
        border-radius: 0 0 0.75rem 0.75rem;
      }
      

      Save your changes to styles.css and open index.html in your browser. The whole unordered list now looks like a box with equal rounded corners. The following images demonstrates how this is rendered in the browser:

      Large bold blue headline followed by an unordered list of eight, items each in a light green box with a green border. The first and last items in the list have rounded corners.

      In this section, you used the last-child pseudo-class to apply styles to the last <li> element in an unordered list. In the next, section you will write styles for when there is only one child element.

      only-child Pseudo-Class Selector

      When applying styles to contents that can change or update, there may be instances when there is only one child element. In those instances, the element is both the first and the last child, which can cause the pseudo-classes to overwrite each other’s styles. For this scenario there is another pseudo-class selector specifically for the only child scenario.

      To start, open index.html in your text editor and add the highlighted HTML from the following code block inside the <main> element and after the previous <section> element:

      index.html

      ...
      <main class="content-width">
        ...
        <section>
          <h2>Only Child Pseudo-Class Selector</h2>  
          <ul>
            <li>Sweet roll pastry carrot cake</li>
          </ul>
        </section>
      </main>
      

      Save the changes to index.thml then return to your browser and refresh the page. The browser is applying the :first-child rounded corners on the top, but then the :last-child rounded corner property overwrites the first. This results in the single list item having sharp corners on top and rounded corners on the bottom. The following image shows the browser rendering of the code:

      Large bold blue headline followed by an unordered list of one item with a light green background, green border, rounded corners on the bottom of the shape.

      Return to your text editor and open styles.css. To address this scenario, you will use the :only-child pseudo-class selector on the li portion of a child combinator. Then, for the border-radius property, set the value to a single 0.75rem, which will apply the curve to all four corners. The highlighted CSS in the following code block shows how this is written:

      styles.css

      ...
      ul > li:last-child {
        border-radius: 0 0  0.75rem 0.75rem;
      }
      
      ul > li:only-child {
        border-radius: 0.75rem;
      }
      

      Save these additions to styles.css, return to your browser, and refresh index.html. The single list item now has rounded corners on all sides, as shown in the following image:

      Large bold purple headline followed by an unordered list of one item with a light green background, green border, rounded corners on all four corners of the shape.

      In this section, you used the only-child pseudo-class selector to apply styles to a single <li> element in an unordered list. In the next section, you will use a pseudo-class selector to apply styles to any specific child element based on its numerical count within the parent.

      nth-child Pseudo-Class Selector

      The nth-child pseudo-class selector allows you to set patterns for the selection of child elements. Other selectors use characteristics of an element, such as an attribute value, to find matching HTML elements. The nth-child pseudo-class selector targets HTML elements by a given numerical position within their parent. The term nth is a mathematical phrase referring to an unidentified number in a series. This particular selector enables the selection of even and odd numbered children and specific numbered elements in the sequence.

      To set up the HTML for this selector, open index.html in your text editor. Then, add the highlighted portion from the following code block after the last </section> tag:

      index.html

      ...
      <main class="content-width">
        ...
        <section>
          <h2>Nth Child Pseudo-Class Selector</h2>
          <ol>
            <li>Caramel marshmallows</li>
            <li>Gummi bears</li>
            <li>pudding donut</li>
            <li>Chocolate bar</li>
            <li>Lemon drops</li>
            <li>Lollipop</li>
            <li>Danish soufflé</li>
          </ol>
        </section>
      </main>
      

      This code sets up an ordered list, as defined by the <ol> element. Unlike the <ul>, which marks each list item with a bullet point, the <ol> marks each item with a number in sequence.

      Be sure to save those changes to index.html. Then return to styles.css in your text editor. You will set up some adjusted stlyes for the ordered list and the list items. Create an ol element selector with a padding property set to 0. Next, add a list-style-position property with a value of inside; this will move the generated number to be inside the <li> element’s box model. Lastly, create an ol li descendant combinator with a padding property set to 0.25rem. Reference the highlighted CSS of the following code block for how this is to be written:

      styles.css

      ...
      ul > li:only-child {
        border-radius: 0.75rem;
      }
      
      ol {
        padding: 0;
        list-style-position: inside;
      }
      
      ol li {
        padding: 0.25rem;
      }
      

      Save your changes to styles.css, then open a web browser and load your index.html file. The new section will be rendered with a list of seven items, each beginning with their numerical value in the sequence, as illustrated in the following image:

      Large bold blue headline followed by an ordered list of seven items in black text.

      To begin working with the nth-child pseudo-class, return to styles.css in your text editor. The selector is set up like the previous pseudo-classes, but with a parenthesis at the end. This parenthesis contains the word value or numeric value to select the elements. To select all the even numbered list items, create a descendant combinator for ol and li. Then, add :nth-child() and inside the parenthesis add the word even. In the selector block, set the background-color property to aliceblue, as highlighted in the following code block:

      styles.css

      ...
      ol li {
        padding: 0.25rem;
      }
      
      ol li:nth-child(even) {
        background-color: aliceblue;
      }
      

      Save your changes to styles.css and open index.html in your browser. The second, fourth, and sixth items in the list now have a light blue background. This is how to create a style known as zebra stripes, which helps legibility with long lists of information. The following image demonstrates how this is rendered in the browser:

      Large bold blue headline followed by an ordered list of seven items in black text, alternating background betwen white and light blue.

      Next, return to styles.css in the text editor and do the same thing for the odd-numbered list items. Create another descendant combinator with the :nth-child() pseudo-class selector. This time, inside the parenthesis add the word value odd. Then in the selector block set the background-color property to lavenderblush, a light pink color. The following highlighted code shows how to set this up:

      styles.css

      ...
      ol li:nth-child(even) {
        background-color: aliceblue;
      }
      
      ol li:nth-child(odd) {
        background-color: lavenderblush;
      }
      

      Save that change to styles.css and reload index.html in the browser. The list now alternates between lavenderblush and aliceblue, with the new color on the first, third, fifth, and seventh list items. The following image shows how this will appear:

      Large bold blue headline followed by an ordered list of seven items in black text, alternating background betwen pink and light blue.

      Lastly, a numeric value can be inserted instead of a word value. Return to styles.css and add another ol li:nth-child() selector, this time with a 4 inside the parentheses. This will select the fourth item in the list. To make that item stand out, add a color property set to white and a background-color property set to indigo, as highlighted in the following code block:

      styles.css

      ...
      ol li:nth-child(odd) {
        background-color: lavenderblush;
      }
      
      ol li:nth-child(4) {
        color: white;
        background-color: indigo;
      }
      

      Save your changes to styles.css and open index.html in your browser. The odd and even items retain their alternating zebra stripe styling, but the fourth item now has a purple-colored background with white text. The following image shows how this is rendered in the browser:

      Large bold blue headline followed by an ordered list of seven items in black text, alternating background between pink and light blue with the fourth item having a purple background with white text.

      Note: The :nth-child() pseudo-class is able to also use algebric equations, such as 3n to select every third item in a list. CSS Tricks has a nth-child testing tool to test nth-child values to help understand the complex versatility of this pseudo-class selector.

      In this last section, you used the :nth-child() pseudo-class selector to apply styles to even-numbered elements, odd-numbered elements, and specifically the fourth element in the list.

      Conclusion

      In this tutorial, you have used many new selectors based on the concept of relationships. You used the descendant combinator and child combinator selectors to select elements inside other elements. Then, you used the general sibling combinator and adjacent sibling combinator to select elements that have a shared parent and apply styles based on proximity. Lastly, you used a series of pseudo-class selectors to style the first, last, and only child elements, along with every nth element in between. These selectors will help you hone and scope the styles of your projects.

      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 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 Customize the Browser’s Scrollbar with CSS


      While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or
      edited it to ensure you have an error-free learning experience. It’s on our list, and we’re working on it!
      You can help us out by using the “report an issue” button at the bottom of the tutorial.

      Introduction

      Custom scrollbars are getting popular, and you might have come across websites that have unique scrollbars, making the sites feel and look different. There are basically a few ways to implement a custom scrollbar.

      In this tutorial we will be using CSS3, which is the most straightforward way. However, there are jQuery plugins that can help with customizing scrollbar, but I do not like to add more JavaScript to my website. If you are a designer, photographer or you just want your website to have a cool scrollbar, go ahead with the jQuery plugins.

      Custom scrollbars are exposed behind the -webkit vendor prefix for use in browsers using the Webkit (and Blink) rendering engine.

      Screenshot depicting the scrollbar-thumb and scrollbar-track parts to a scrollbar.

      -webkit-scrollbar consists of seven different pseudo-elements, and together comprise a full scrollbar UI element:

      1. ::-webkit-scrollbar the background of the bar itself.
      2. ::-webkit-scrollbar-button the directional buttons on the scrollbar.
      3. ::-webkit-scrollbar-track the empty space “below” the progress bar.
      4. ::-webkit-scrollbar-track-piece the top-most layer of the the progress bar not covered by the thumb.
      5. ::-webkit-scrollbar-thumb the draggable scrolling element resizes depending on the size of the scrollable element.
      6. ::-webkit-scrollbar-corner the bottom corner of the scrollable element, where two scrollbar meet.
      7. ::-webkit-resizer the draggable resizing handle that appears above the scrollbar-corner at the bottom corner of some elements.

      Now that you are familiar with the terminologies, let’s start!

      Setting Up the Project

      First, create index.html and style.css files, and open the current directory with your code editor.

      index.html

      <!DOCTYPE html>
      <html>
          <head>
              <meta charset="UTF-8" />
              <title>Customize the Browser's Scrollbar with CSS</title>
              <link type="text/css" rel="stylesheet" href="https://www.digitalocean.com/community/tutorials/styles.css">
          </head>
          <body>
              <div class="scrollbar" id="style-1">
                  <div class="force-overflow"></div>
              </div>
          </body>
      </html>
      

      You’ll need to include the style.css file in the HTML file. You can type out the above HTML code or just copy and paste into your HTML file.

      Firstly, we set the .scrollbar (class) width, height, background-color, then set overflow-y: scroll to get the vertical scrollbar. We set min-height: 450px to the .force-overflow div so that the scrollbar appears (because we used the overflow-y property to scroll in .scrollbar class).

      styles.css

      .scrollbar {
          background-color: #F5F5F5;
          float: left;
          height: 300px;
          margin-bottom: 25px;
          margin-left: 22px;
          margin-top: 40px;
          width: 65px;
          overflow-y: scroll;
      }
      
      .force-overflow {
          min-height: 450px;
      }
      

      Screenshot depicting the current default appearance of the scrollbar.

      Now, we use the scrollbar pseudo-element for creating our custom scrollbar. It will replace its default width with a new width of 6px and then add background-color: #F5F5F5.

      styles.css

      #style-1::-webkit-scrollbar {
          width: 6px;
          background-color: #F5F5F5;
      }
      

      Since we know that scrollbar contains track, button and thumb, we are now going to give a stylish look to thumb. We use pseudo-element (i.e., ::-webkit-scrollbar-thumb) with -webkit prefix and set scrollbar-thumb background- color.

      styles.css

      #style-1::-webkit-scrollbar-thumb {
          background-color: #000000;
      }
      

      After that, the scrollbar looks like this:

      Screenshot of the modified scrollbar with a black scrollbar-thumb.

      We use box-shadow on scrollbar-track to make it stylish and add contrast between the scrollbar and scrollbar-track.

      styles.css

      #style-1::-webkit-scrollbar-track {
          -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
          background-color: #F5F5F5;
      }
      

      Screenshot of the modified scrollbar with a black scrollbar-thumb and light-colored scrollbar-track.

      Conclusion

      In this article, we covered:

      • Customized scrollbars aren’t uncommon anymore. You will find them in major websites and blogs, especially personal portfolio websites.
      • There are tons of jQuery plugins that can help with customizing scrollbar.
      • Custom scrollbars are exposed behind the -webkit vendor prefix.
      • Basic structure of a scrollbar.
      • Terminologies associated with scrollbars.

      The CSS way of customizing scrollbars is simple, but looks a bit rough. However, operating systems like Windows, OS X and Linux have their own style for the scrollbar. This in return could lead to undesirable results and inconsistencies for your design. Remember, you should keep it simple, stupid (KISS), not too fancy.

      I have created more scrollbars using the above procedure. I made use of codePen for the demo, and you can find the full code for this tutorial on CodePen.

      Screenshot of a demo with many customized scrollbars in different colors and sizes.

      That’s all. I hope you like it!

      Make sure to leave any thoughts, questions or concerns in the comments below. I would love to see them.

      Acknowledgements

      @twholman Codepen





      Source link