One place for hosting & domains

      Select

      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 Query the Database in Laravel with Eloquent (Select)



      Part of the Series:
      A Practical Introduction to Laravel Eloquent ORM

      Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. In this project-based series, you’ll learn how to make database queries and how to work with relationships in Laravel Eloquent. To practice the examples explained throughout the series, you’ll improve a demo application with new models and relationships.

      If you’ve been following along with all parts of this series so far, you should have the application’s database and commands upgraded to include lists of links.

      The application main route currently shows all links in the database, with no information about lists. In this section, you’ll update the main front end view in order to reflect the new architecture.

      One of the biggest advantages of using an ORM system is the ability to manipulate rows in a database table as objects within your codebase. Eloquent provides several methods that can be accessed directly from models to query the database and filter results without having to write SQL statements. A typical SELECT query to obtain all rows from a table, which in pure SQL looks something like SELECT * FROM links, can be accomplished in Eloquent with code like this:

      $links = Link::all();
      

      The result set is returned as an Eloquent Collection, an iterable object that behaves similarly to an array, but provides extended functionality such as map / reduce methods and the ability to “hydrate” (pull in fresh data) referenced objects only when needed, which helps with overall performance while interacting with the database.

      Updating the Index Route

      If you examine the main application route file, where the index route is defined, you’ll notice that the current application code queries all links using a Link::all() call. Open the routes/web.php file in your code editor:

      routes/web.php
      

      This is how the / route is currently defined in this file:

      routes/web.php

      …
      Route::get('/', function () {
          $links = Link::all()->sortDesc();
          return view('index', [
              'links' => $links
          ]);
      });
      …
      

      As the name suggests, the sortDesc() method is used for ordering results in descending order, from last to first. This is not the same as an ORDER BY clause in an SQL query, since the sortDesc method works at code level, reordering the collection. You can ignore this method for now, as we’ll talk more about ordering results in an upcoming section of this series.

      You’ll now edit this code to obtain a collection of all lists currently registered within the database, so that you can use it later on in the front end view to show all list names.

      First, include a use declaration at the beginning of the file, referencing the LinkList model. This declaration is used to make sure that you don’t need to type the full class name each time you reference that class.

      routes/web.php

      <?php
      
      use IlluminateSupportFacadesRoute;
      use AppModelsLink;
      use AppModelsLinkList;
      ...
      

      Then, change the return of the main route definition to include a lists variable containing all registered lists:

      routes/web.php

      …
          return view('index', [
              'links' => $links,
              'lists' => LinkList::all()
          ]);
      …
      

      This is how the finished file should look. Note the highlighted changes:

      routes/web.php

      <?php
      
      use IlluminateSupportFacadesRoute;
      use AppModelsLink;
      use AppModelsLinkList;
      
      /*
      |--------------------------------------------------------------------------
      | Web Routes
      |--------------------------------------------------------------------------
      |
      | Here is where you can register web routes for your application. These
      | routes are loaded by the RouteServiceProvider within a group which
      | contains the "web" middleware group. Now create something great!
      |
      */
      
      Route::get('/', function () {
          $links = Link::all()->sortDesc();
          return view('index', [
              'links' => $links,
              'lists' => LinkList::all()
          ]);
      });
      
      

      Don’t forget to save the file when you’re done updating it.

      Updating the Index View

      Once you get the main route updated to also provide information about lists, you can edit the referenced view file. Open the resources/views/index.blade.php file in your code editor:

      resources/views/index.blade.php
      

      This file contains the single front end view file that the application uses in its main index page. Within this file, locate the @foreach blade block that loops over the $links variable. It will look like this:

      resources/views/index.blade.php

      ...
                  @foreach ($links as $link)
                      <div class="box link">
                          <h3><a href="https://www.digitalocean.com/community/tutorials/{{ $link->url }}" target="_blank" title="Visit Link: {{ $link->url }}">{{ $link->description }}</a></h3>
                          <p>{{$link->url}}</p>
                      </div>
                  @endforeach
      ...
      

      The code in the loop does not include any information about lists yet. You’ll now include a new line right after the link URL that contains the title of the list where that link is saved. You can use the tag CSS class from Bulma to style this information as a tag:

      resources/views/index.blade.php

      …
      <p>{{$link->url}}</p>
      <p class="mt-2"><a href="#" title="{{ $list->title }}" class="tag is-info">{{ $link->link_list->title }}</a></p>

      Add the highlighted line to your file. The links will be adjusted later on, when you set up individual list pages in an upcoming part of this series.

      Next, locate the paragraph that has the class subtitle, which comes right after the <h1> tag and before the section containing your links. You’ll replace the generic text used in that area with a menu based on your link lists, which you made available previously in a lists variable when you edited the default route in routes/web.php.

      Replace the text in the subtitle section with the highlighted content:

      resources/views/index.blade.php

      
              <p class="subtitle">
                  @foreach ($lists as $list)<a href="#" title="{{ $list->title }}" class="tag is-info is-light">{{ $list->title }}</a> @endforeach
              </p>
      

      The list tags are styled just slightly differently than before, with an is-light additional CSS class to invert the colors of each tag.

      This is how your index.blade.php file should look like after you’re done editing. The highlighted lines indicate the changes:

      resources/views/index.blade.php

      <!DOCTYPE html>
      <html>
      <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <title>My Awesome Links</title>
          <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.1/css/bulma.min.css">
      
          <style>
              html {
                  background: url("https://i.imgur.com/BWIdYTM.jpeg") no-repeat center center fixed;
                  -webkit-background-size: cover;
                  -moz-background-size: cover;
                  -o-background-size: cover;
                  background-size: cover;
              }
      
              div.link h3 {
                  font-size: large;
              }
      
              div.link p {
                  font-size: small;
                  color: #718096;
              }
          </style>
      </head>
      <body>
      <section class="section">
          <div class="container">
              <h1 class="title">
                  Check out my awesome links
              </h1>
              <p class="subtitle">
                  @foreach ($lists as $list)<a href="#" title="{{ $list->title }}" class="tag is-info is-light">{{ $list->title }}</a> @endforeach
              </p>
      
              <section class="links">
                  @foreach ($links as $link)
                      <div class="box link">
                          <h3><a href="https://www.digitalocean.com/community/tutorials/{{ $link->url }}" target="_blank" title="Visit Link: {{ $link->url }}">{{ $link->description }}</a></h3>
                          <p>{{$link->url}}</p>
                          <p class="mt-2"><a href="#" title="{{ $list->title }}" class="tag is-info">{{ $link->link_list->title }}</a></p>
                      </div>
                  @endforeach
              </section>
          </div>
      </section>
      </body>
      </html>
      
      

      Save the file when you’re done. The main front end view is now ready to show updated information about link lists.

      If you’d like, you can use the link:new Artisan command now to include new links and test your updated application:

      • docker-compose exec app php artisan link:new
      [secondary_label Output
      Link URL:
      > https://laravel.com/docs/8.x/
      
      Link Description:
      > Laravel Docs
      
      Link List (leave blank to use default):
      > laravel
      
      New Link:
      https://laravel.com/docs/8.x/ - Laravel Docs
      Listed in: laravel
      
      Is this information correct? (yes/no) [no]:
      > yes
      
      Saved.
      

      Then, reload the application page on your browser. If you’re using the included Docker Compose setup, the application should be available on the following local address:

      http://localhost:8000
      

      You’ll obtain a page similar to this:

      Screenshot of Landing Laravel app, updated to support link lists

      In the next part of this series, you’ll set up individual pages for link lists and learn how to make queries to the database using the where() method, for more fine-grained results.

      This tutorial is part of an ongoing weekly series about Laravel Eloquent. You can subscribe to the Laravel tag if you want to be notified when new tutorials are published.



      Source link

      How To Select HTML Elements Using ID, Class, and Attribute Selectors in CSS


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

      Introduction

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

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

      Prerequisites

      Setting Up the Base HTML and CSS

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

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

      index.html

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

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

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

      index.html

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

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

      index.html

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

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

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

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

      styles.css

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

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

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

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

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

      Using the ID Selector

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

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

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

      index.html

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

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

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

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

      styles.css

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

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

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

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

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

      Using the Class Selector

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

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

      index.html

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

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

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

      styles.css

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

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

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

      index.html

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

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

      index.html

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

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

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

      styles.css

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

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

      styles.css

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

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

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

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

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

      index.html

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

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

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

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

      Combining Class Selectors

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

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

      styles.css

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

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

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

      index.html

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

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

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

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

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

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

      Add the following highlighted sections to your CSS file:

      styles.css

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

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

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

      index.html

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

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

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

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

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

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

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

      Using the Attribute Selector

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

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

      index.html

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

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

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

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

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

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

      styles.css

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

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

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

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

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

      styles.css

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

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

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

      Creating Advanced Attribute Selectors

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

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

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

      styles.css

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

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

      Link text in green color with underline.

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

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

      styles.css

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

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

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

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

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

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

      styles.css

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

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

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

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

      Conclusion

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

      If you would like to read more CSS tutorials, try out the other tutorials in the How To Style HTML with CSS series.



      Source link