One place for hosting & domains

      Elements

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


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

      Introduction

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

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

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

      Prerequisites

      Setting Up the Example HTML

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

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

      index.html

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

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

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

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

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

      To have proper HTML semantics:

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

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

      index.html

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

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

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

      index.html

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

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

      index.html

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

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

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

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

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

      Using the font-family Property

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

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

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

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

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

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

      styles.css

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

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

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

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

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

      Loading Custom Fonts With Google Fonts

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

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

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

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

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

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

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

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

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

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

      index.html

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

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

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

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

      styles.css

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

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

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

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

      index.html

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

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

      styles.css

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

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

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

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

      Using font-weight and font-style Properties

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

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

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

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

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

      styles.css

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

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

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

      styles.css

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

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

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

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

      styles.css

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

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

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

      styles.css

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

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

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

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

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

      Using the font-size Property

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

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

      styles.css

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

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

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

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

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

      styles.css

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

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

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

      styles.css

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

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

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

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

      Using the color Property to Distinguish Text

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

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

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

      styles.css

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

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

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

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

      styles.css

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

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

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

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

      styles.css

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

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

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

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

      Conclusion

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

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



      Source link

      Comment créer des éléments par glisser-déposer avec Vanilla JavaScript et HTML


      Introduction

      Le glisser-déposer est une interaction utilisateur courante que vous pouvez trouver dans de nombreuses interfaces graphiques.

      Il existe des bibliothèques JavaScript préexistantes permettant d’ajouter une fonction de glisser-déposer à votre application. Toutefois, il peut arriver qu’une bibliothèque ne soit pas disponible ou qu’elle introduise une surcharge ou une dépendance dont votre projet n’a pas besoin. Dans de telles situations, la connaissance des API dont vous disposez dans les navigateurs web modernes peut vous offrir des solutions alternatives.

      L’API HTML Drag and Drop s’appuie sur le modèle d’événement de DOM pour obtenir des informations sur ce qui est glissé ou déposé et pour mettre à jour cet élément par glisser-déposer. Grâce aux gestionnaires d’événements JavaScript, vous pouvez transformer n’importe quel élément en un élément pouvant être glissé ou déposé.

      Dans ce tutoriel, nous allons construire un exemple de glisser-déposer en utilisant l’API HTML Drag and Drop avec Vanilla JavaScript pour utiliser les gestionnaires d’événements.

      Conditions préalables

      Pour suivre ce tutoriel, vous aurez besoin de :

      • Un navigateur web moderne qui supporte l’API Drag and Drop (Chrome 4+, Firefox 3.5+, Safari 3.1+, Edge 18+).

      Étape 1 – Création du projet et balisage initial

      Notre projet consistera en un conteneur avec deux types d’éléments enfant :

      • Des éléments enfant que vous pouvez faire glisser
      • Des éléments enfant dans lesquels il est possible de déposer des éléments

      Tout d’abord, ouvrez la fenêtre de votre terminal et créez un nouveau répertoire de projets :

      • mkdir drag-and-drop-example

      Ensuite, naviguez vers ce répertoire :

      Puis créez un fichier index.html dans ce répertoire :

      Ajoutez maintenant du code passe-partout pour une page web HTML :

      index.html

      <!DOCTYPE html>
      <html>
        <head>
          <title>My Drag-and-Drop Example</title>
          <link rel="stylesheet" href="https://www.digitalocean.com/community/tutorials/style.css" />
        </head>
        <body>
        </body>
      </html>
      

      Et entre les balises <body> ajoutez votre élément draggable et votre dropzone (cible de largage) :

      index.html

      <div class="example-parent">
        <div class="example-origin">
          <div
            id="draggable-1"
            class="example-draggable"
          >
            draggable
          </div>
        </div>
      
        <div
          class="example-dropzone"
        >
          dropzone
        </div>
      </div>
      

      Enregistrez et fermez le fichier. Ensuite, créez un fichier style.css :

      Puis, ajoutez des styles pour les éléments de notre fichier index.html :

      style.css

      .example-parent {
        border: 2px solid #DFA612;
        color: black;
        display: flex;
        font-family: sans-serif;
        font-weight: bold;
      }
      
      .example-origin {
        flex-basis: 100%;
        flex-grow: 1;
        padding: 10px;
      }
      
      .example-draggable {
        background-color: #4AAE9B;
        font-weight: normal;
        margin-bottom: 10px;
        margin-top: 10px;
        padding: 10px;
      }
      
      .example-dropzone {
        background-color: #6DB65B;
        flex-basis: 100%;
        flex-grow: 1;
        padding: 10px;
      }
      

      Cela permettra d'ajouter un certain formatage à l'application. Vous pouvez maintenant visualiser index.html dans le navigateur et observer que cela produit un dragable <div> et un dropzone <div>.

      Capture d'écran des div draggable et dropzone

      Ensuite, nous rendrons explicitement le premier <div> glissant en ajoutant l'attribut draggable :

      index.html

      <div class="example-parent">
        <div class="example-origin">
          <div
            id="draggable-1"
            class="example-draggable"
            draggable="true"
          >
            draggable
          </div>
        </div>
      
        <div
          class="example-dropzone"
        >
          dropzone
        </div>
      </div>
      

      Enregistrez et fermez le fichier.

      Enfin, regardez à nouveau index.html dans le navigateur. Si nous cliquons sur le draggable <div> et le faisons glisser sur l'écran, il doit y avoir une indication visuelle de son déplacement.

      La valeur par défaut de l'attribut draggable est auto. Cela signifie que la possibilité de faire glisser l'élément sera déterminée par le comportement par défaut de votre navigateur. En général, cela signifie que les sélections de texte, les images et les liens peuvent être glissés sans qu'il soit nécessaire de spécifier draggable=" true".

      Vous avez maintenant un fichier HTML avec un élément glissant. Nous passerons à l'ajout de gestionnaires onevents.

      Étape 2 - Gestion des événements par glisser-déposer avec JavaScript

      Actuellement, si nous relâchons la souris tout en faisant glisser l'élément déplaçable, il ne se passe rien. Pour déclencher une action sur les éléments du DOM par glisser-déposer, nous devons utiliser l'API Drag and Drop :

      • ondragstart : ce gestionnaire d'événement sera attaché à notre élément draggable et se déclenchera lorsqu'un événement dragstart se produira.
      • ondragover : ce gestionnaire d'événements sera attaché à notre élément dropzone et se déclenchera lorsqu'un événement dragover se produira.
      • ondrop : ce gestionnaire d'événements sera également attaché à notre élément dropzone et se déclenchera lorsqu'un événement drop se produira.

      Remarque : il y a huit gestionnaires d'événements au total : ondrag, ondragend, ondragenter, ondragexit, ondragleave, ondragover, ondragstart et ondrop. Dans le cadre de notre exemple, nous n'aurons pas besoin de tous.

      Tout d'abord, référençons un nouveau fichier script.js dans notre index.html :

      index.html

      <body>
        ...
        <script src="https://www.digitalocean.com/community/tutorials/script.js"></script>
      </body>
      

      Ensuite, nous allons créer un nouveau fichier script.js :

      L'objet DataTransfer conservera les informations relatives à la traînée actuelle. Pour mettre à jour notre élément par glisser-déposer, nous devons accéder directement à l'objet DataTransfer. Pour ce faire, nous pouvons sélectionner la propriété dataTransfer de l'élément DOM DragEvent.

      Remarque : l'objet DataTransfer peut techniquement suivre les informations de plusieurs éléments glissés en même temps. Dans le cadre de notre exemple, nous nous concentrerons sur le glissement d'un élément.

      La méthode setData de l'objet dataTransfer peut être utilisée afin de définir les informations d'état de glissement pour votre élément actuellement glissé. Il faut deux paramètres :

      • une chaîne qui déclare le format du deuxième paramètre
      • les données réelles transférées

      Notre objectif est de déplacer notre élément draggable vers un nouvel élément parent. Nous devons pouvoir sélectionner notre élément draggable avec un identifiant unique. Nous pouvons définir l’identifiant de l'élément glissé avec la méthode setData pour qu'il puisse être utilisé plus tard.

      Revisitons notre fichier script.js et créons une nouvelle fonction pour utiliser setData :

      script.js

      function onDragStart(event) {
        event
          .dataTransfer
          .setData('text/plain', event.target.id);
      }
      

      Remarque : Internet Explorer 9 à 11 aurait des problèmes avec l'utilisation de "text/plain". Le format doit être 'text' pour ce navigateur.

      Pour mettre à jour le style CSS de l'élément glissé, nous pouvons accéder à ses styles en utilisant à nouveau l'événement DOM et en définissant les styles que nous voulons pour la currentTarget.

      Ajoutons-les à notre fonction et changeons la backgroundColor en yellow :

      script.js

      function onDragStart(event) {
        event
          .dataTransfer
          .setData('text/plain', event.target.id);
      
        event
          .currentTarget
          .style
          .backgroundColor="yellow";
      }
      

      Remarque : tous les styles que vous modifiez devront être à nouveau mis à jour manuellement sur drop si vous souhaitez des styles par glisser-déposer. Si vous changez quelque chose quand il commence à glisser, l'élément glissé conservera ce nouveau style à moins que vous ne le changiez à nouveau.

      Maintenant, nous avons notre fonction JavaScript pour le démarrage du glissement.

      Nous pouvons ajouter ondragstart à l'élément draggable dans index.html :

      index.html

      <div class="example-parent">
        <div class="example-origin">
          <div
            id="draggable-1"
            class="example-draggable"
            draggable="true"
            ondragstart="onDragStart(event);"
          >
            draggable
          </div>
        </div>
      
        <div class="example-dropzone">
          dropzone
        </div>
      </div>
      

      Consultez index.html dans votre navigateur. Si vous essayez de faire glisser votre objet maintenant, le style déclaré dans notre fonction sera appliqué :

      Gif animé représentant un élément se faisant glisser mais ne pouvant pas être déposer

      Cependant, rien ne se passera lorsque vous relâcherez votre clic.

      Le prochain gestionnaire d'événements déclenché dans cette séquence est ondragover.

      Le comportement par défaut de certains éléments DOM comme <div> dans les navigateurs n'accepte généralement pas d'être déposé. Ce comportement interceptera le comportement que nous essayons de mettre en œuvre. Pour nous assurer que nous obtenons le comportement drop souhaité, nous appliquerons preventDefault.

      Revisitons notre fichier script.js et créons une nouvelle fonction pour utiliser preventDefault. Ajoutez ce code à la fin du fichier :

      script.js

      function onDragOver(event) {
        event.preventDefault();
      }
      

      Maintenant, nous pouvons ajouter ondragover à notre élément dropzone dans index.html :

      index.html

      <div class="example-parent">
        <div class="example-origin">
          <div
            id="draggable-1"
            class="example-draggable"
            draggable="true"
            ondragstart="onDragStart(event);"
          >
            draggable
          </div>
        </div>
      
        <div
          class="example-dropzone"
          ondragover="onDragOver(event);"
        >
          dropzone
        </div>
      </div>
      

      À ce stade, nous n'avons toujours pas de code écrit pour gérer le dépôt réel. Le dernier gestionnaire d'événements déclenché dans cette séquence est ondrop.

      Revoyons notre fichier script.js et créons une nouvelle fonction.

      Nous pouvons référencer les données que nous avons enregistrées précédemment avec la méthode setData de l'objet dataTransfer. Nous utiliserons la méthode getData de l'objet dataTransfer. Les données que nous avons établies étaient l’id, c'est donc ce qui nous sera renvoyé :

      script.js

      function onDrop(event) {
        const id = event
          .dataTransfer
          .getData('text');
      }
      

      Sélectionnons notre élément draggable avec l’id que nous avons récupéré :

      script.js

      function onDrop(event) {
        // ...
      
        const draggableElement = document.getElementById(id);
      }
      

      Sélectionnons notre élément dropzone :

      script.js

      function onDrop(event) {
        // ...
      
        const dropzone = event.target;
      }
      

      Ajoutons notre élément draggable à la dropzone :

      script.js

      function onDrop(event) {
        // ...
      
        dropzone.appendChild(draggableElement);
      }
      

      Réinitialisons notre objet DataTransfer :

      script.js

      function onDrop(event) {
        // ...
      
        event
          .dataTransfer
          .clearData();
      }
      

      Maintenant, nous pouvons ajouter ondrop à notre élément dropzone dans index.html :

      index.html

      <div class="example-parent">
        <div class="example-origin">
          <div
            id="draggable-1"
            class="example-draggable"
            draggable="true"
            ondragstart="onDragStart(event);"
          >
            draggable
          </div>
        </div>
      
        <div
          class="example-dropzone"
          ondragover="onDragOver(event);"
          ondrop="onDrop(event);"
        >
          dropzone
        </div>
      </div>
      

      Une fois que cela est fait, nous avons une fonction de glisser-déposer fonctionnelle. Affichez index.html dans votre navigateur et faites glisser l'élément draggable sur la dropzone.

      Gif animé représentant un élément glissé et déposé dans une cible de largage

      Notre exemple porte sur le scénario d'un seul objet pouvant être déplacé et d'une seule cible de largage. Vous pouvez avoir plusieurs objets à faire glisser, plusieurs cibles où les déposer, et personnaliser tout cela avec tous les autres gestionnaires d'événements de l'API Drag and Drop.

      Étape 3 - Construction d'un exemple complexe avec plusieurs éléments glissants

      Voici un autre exemple de la manière dont vous pourriez utiliser cette API : une liste de tâches avec des tâches glissantes que vous pouvez déplacer d'une colonne "To-do" à une colonne "Done".

      Gif animé représentant plusieurs tâches glissées et déposées dans une colonne Done

      Pour créer votre propre liste de tâches, ajoutez à index.html d'autres éléments à faire glisser avec des ids uniques :

      index.html

      <div class="example-parent">
        <h1>To-do list</h1>
        <div class="example-origin">
          To-do
          <div
            id="draggable-1"
            class="example-draggable"
            draggable="true"
            ondragstart="onDragStart(event);"
          >
            thing 1
          </div>
          <div
            id="draggable-2"
            class="example-draggable"
            draggable="true"
            ondragstart="onDragStart(event);"
          >
            thing 2
          </div>
          <div
            id="draggable-3"
            class="example-draggable"
            draggable="true"
            ondragstart="onDragStart(event);"
          >
            thing 3
          </div>
          <div
            id="draggable-4"
            class="example-draggable"
            draggable="true"
            ondragstart="onDragStart(event);"
          >
            thing 4
          </div>
        </div>
      
        <div
          class="example-dropzone"
          ondragover="onDragOver(event);"
          ondrop="onDrop(event);"
        >
          Done
        </div>
      </div>
      

      Affichez index.html dans votre navigateur et faites glisser les éléments de la colonne To-do vers la colonne Done. Vous avez créé une application to-do et testé la fonctionnalité.

      Conclusion

      Dans cet article, vous avez créé une application to-do pour explorer la fonctionnalité de glisser-déposer qui est disponible pour les navigateurs web modernes.

      L'API Drag and Drop offre de multiples options pour personnaliser vos actions au-delà du simple glisser-déposer. Par exemple, vous pouvez mettre à jour le style CSS de vos éléments glissés. Vous pouvez également, au lieu de déplacer l'élément, choisir de copier votre élément déplaçable afin qu'il soit reproduit lors du dépôt.

      Gardez à l'esprit que si de nombreux navigateurs web prennent en charge cette technologie, vous ne pourrez peut-être pas vous y fier si votre public se compose d’appareils qui ne prennent pas en charge cette fonctionnalité.

      Pour en savoir plus sur tout ce que vous pouvez déposer avec l'API Drag and Drop, consultez les documents du MDN à ce sujet.



      Source link

      How To Select HTML Elements to Style with CSS


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

      Introduction

      The core functionality of CSS is performed by two features: cascade and specificity. Cascade deals with how CSS properties are read and applied to elements. Specificity directs a browser to find the correct element and apply the styles. The starting point of specificity is a selector, which tells the browser what element to find. When it comes to styling, the larger a web page or website, the greater the need for more specific, or higher specificity, selectors.

      Selecting the right element and providing the right visual styles is the basis of writing CSS code. Whenever you need to adjust how an element on a webpage looks, using selectors is key.

      This tutorial will build your skill set and help you develop visually rich websites by showing you how to select the right element in a given scenario. You will begin by using the type selector to select HTML elements to style. Then, you will combine selectors to identify and apply styles more precisely. Lastly, you will group several selectors to apply the same styles to different elements.

      Prerequisites

      Setting Up the HTML

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

      Open up the index.html file in your editor and add the following boilerplate HTML to give the file necessary baseline code:

      index.html

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

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

      Now, you need some content. Start by adding in <header> and <article> elements inside the <body> element. In the following code block, highlighted sections will help you identify what is new or has changed:

      index.html

      <!doctype html>
      <html>
        ...
        <body>
          <header></header>
          <article></article>
        </body>
      </html>
      

      The relationship between the <body> and the <header> elements is referred to as parent and child, since the <header> element is nested inside the <body> tags. This also means the <header> and <article> tag have a sibling relationship, since they are at the same nesting level within the parent <body> tags.

      Next, you will add a child element within the <header> to give the page a title:

      index.html

      ...
      <header>
        <h1>About Coral Reefs</h1>
      </header>
      ...
      

      Inside <article>, add four children: one <header> element and three <section> elements. The <article> element provides what is called a landmark, a designation for a browser to aid those using assistive technologies. There should only be one <header> within a landmark. In this case the <header> will contain the title for this article of the page. The <section> elements will contain different information blocks:

      index.html

      ...
      <article>
        <header></header>
        <section></section>
        <section></section>
        <section></section>
      </article>
      ...
      

      Now, provide a title in the <header> for the <article>. Use an <h2> here since it logically works as a second-level heading beneath the <body>’s <header> with a top-level heading. Add in <strong> tags around the word “Biodiversity” to strongly emphasize the text. When you load index.html in your browser, this text won’t look any different due to the browser defaults. You will style this later to distinguish between the heading and the <strong> text.

      index.html

      ...
      <article>
        <header>
          <h2>Coral Reef <strong>Biodiversity</strong></h2>
        </header>
        ...
      </article>
      ...
      

      Next, add in the first section content. This will be two paragraphs, contained in <p> tags giving some details about coral reefs. In the first paragraph, add an <em> tag and a <strong> tag around some phrases to emphasize that content:

      index.html

      ...
      <article>
        <header>
          ...
        </header>
        <section>
          <p>Coral reefs are teeming with life. They are known as the <em>rainforests of the sea</em> with how many various speieces live within their waters. The defining feature of these ecosystems are the plant-like coral, which are really colonies of tiny invertabrates called <strong>polyps</strong>.</p>
          <p>Sadly, many reefs around the world are in danger due to rising ocean temperatures, pollution, and overfishing.</p>
        </section>
        ...
      </article>
      ...
      

      In the second section, add an <h3> tag for a heading for this section of the article. Like the <h2> before, this is set as an <h3> since it is a subset of content. In the <h3>, add a <strong> tag around a phrase in the heading like in the <h2>. Then write out an unordered list using the <ul> tag to define the list and <li> to define each item in the list. In one of the list items, wrap the content in a <strong> tag:

      index.html

      ...
      <article>
        <header>
          ...
        </header>
        <section>
          ...
        </section>
        <section>
          <h3><strong>Animal Life</strong> in a Coral Reef</h3>
          <ul>
            <li>Angelfish</li>
            <li>Clownfish</li>
            <li>Octopus</li>
            <li><strong>Sharks</strong></li>
            <li>Barracuda</li>
          </ul>
        </section>
        ...
      </article>
      ...
      

      With the last section, set up content similar to the second section with an <h3> section title and a <strong> element around a word in the title. Instead of an unordered list, make an ordered list with an <ol> tag to define the list, but still define each item with the <li> tag. Once again, in one of the list items, add a <strong> element around the content:

      index.html

      ...
      <article>
        <header>
          ...
        </header>
        <section>
          ...
        </section>
        <section>
          ...
        </section>
        <section>
          <h3>Sammy's <strong>Favorite</strong> Reef Food</h3>
          <ol>
            <li>Sea Grass</li>
            <li><strong>Kelp</strong></li>
            <li>Sea Grapes</li>
            <li>Sea Lettuce</li>
          </ol>
        </section>
      </article>
      ...
      

      Save your file.

      That covers the HTML for this tutorial and provides elements for which you can begin to write styles. Now that you have finished with index.html, leave it open in your editor for reference as needed. Then open index.html in your browser to see the default styles of your browser, which will appear similar to the following image:

      The content of the website in the browser default rendering with black serif font on a white background.

      Next, you’ll apply styles to the HTML page you created.

      Selecting Elements With the Type Selector

      In this section, you will work with the type selector, more commonly referred to as the element selector. The type selector finds elements on the page by tag name, making it broadest in terms of specificity. You will write several selectors to learn the breadth of this selector throughout the index.html page.

      First, take a look at index.html in the browser. This what the page looks like using browser defaults. These are predefined styles provided by the browser to give visual information to the content of the page. This is a helpful starting place for the styles; in the examples ahead you will only modify a couple of properties to customize the look of the page.

      Next, open the styles.css file in your editor. The default browser font is typically a serif font, a typography term referring to the decorative ends on the characters, like those found in Times New Roman. To change the font across the whole page, you can make a change in one place.

      Create a type selector for the HTML <body> element by typing out the word in the tag, body, followed by an opening and closing curly brace. Inside the curly braces, add a new line and then add the CSS property font-family with a value of sans-serif. This addition of the font-family will change the font for the whole document to a sans serif font. Unlike a serif font, a sans serif font lacks decorative ends on the characters, such as in Helvetica or Arial:

      styles.css

      body {
        font-family: sans-serif;
      }
      

      Once you have made these changes, save styles.css and refresh your browser to verify the text has all changed to the browser’s default sans-serif font. The reason the font changed throughout the whole page is due to a feature of CSS called inheritance. Inheritance is when a child element inherits property values from the parent element, unless otherwise specified. This feature does not affect all CSS properties or elements, but it is most notable among properties that affect text.

      Next, adjust the font-weight of the <h2> and <h3> elements on the page. By default, the browser applies styles to make these elements a bold font. Create an h2 and an h3 type selector and in each add the font-weight property with a value of normal. This will change the default from bold to a normal weight:

      styles.css

      body {
        font-family: sans-serif;
      }
      
      h2 {
        font-weight: normal;
      }
      
      h3 {
        font-weight: normal;
      }
      

      Save and return to your browser and refresh the index.html page. The content of the <h2> and <h3> elements have changed from a bold to a normal font weight, except for the text in the <strong> elements. This is a case where an explicit value is set for the font-weight in the browser defaults, so the <strong> element does not inherit the change to its parent element.

      The primary purpose with any design is to aid in communication. In this case, the design is working to emphasize a particular part of the content through contrasts in font weight. Next, you will apply color to help encourage this contrast. Start with an em type selector and apply a background-color of yellow to give it a highlighter effect. Next, to help draw further attention to the <strong> content, create a strong type selector with a color property set to red:

      styles.css

      ...
      h3 {
        font-weight: normal;
      }
      
      em {
        background-color: yellow;
      }
      
      strong {
        color: red;
      }
      

      Save styles.css and refresh index.html in your browser to find the changes you have made to the design of the website. As shown in the following image, the whole of the text on the page has changed to a sans-serif font, the <h2> and <h3> content headings are no longer bold, all the <strong> element content is now red, and the <em> element content has a yellow highlighter background:

      Content of website in a black sans-serif font, with bold content in red and italic content with a yellow background.

      In this step you worked with multiple type selectors to create specific styles for each selector. The type selector tells the browser to find an element by the element’s name and is the broadest in specificity. Next, you will learn about simplifying your CSS through the use of selector groups.

      Selecting Elements With the Combinator Selector

      In this section, you will work with the combinator selector to make more specific element selection. This selector uses the nested relationship of HTML elements to select the appropriate element. You will use this selector to make the same element type look different when contained in other element types.

      Open up index.html in the browser. As you look over the styles, there are pops of red every so often due to the strong selector that is applying color: red; to all instances of <strong> on the page. In this step you will work through to change the color value on <strong> elements when they meet certain criteria, based on their ancestry, a series of parent and child element relationships.

      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 scope, or provide sufficient specificity, to the intended element. To understand how combinator selectors work, open styles.css and add at the bottom of the file a p type selector followed by a space, then a strong type selector followed by an open and close curly bracket:

      styles.css

      ...
      p strong {
      }
      

      This is a combinator selector that is targeting <strong> elements that are ancestrally descendent of a <p> element. This means the <p> element does not have to be the direct parent of the <strong> element in order for this combinator selector to be true. Now change the color of <strong> elements that meet this criteria by placing a color property within the combinator selector:

      styles.css

      ...
      p strong {
        color: coral;
      }
      

      Save the changes and return to the browser to refresh index.html.

      Content of website in a black sans-serif font, with bold content in red and italic content with a yellow background, except the bold content in a paragraph, which is light orange.

      Next, add more variety of color to the <strong> elements throughout the file. Start with the <strong> element that is a descendant of an <h3> and turn those blue:

      styles.css

      ...
      p strong {
        color: coral;
      }
      
      h3 strong {
        color: blue;
      }
      

      Finally, to add some more color, change the color for <strong> elements in an unordered list to dodgerblue, which is a rich light blue, and the color for <strong> elements in an ordered list to green. Here is where it is helpful to understand ancestry requirements of a combinator selector. You may think you would need to write out ul li strong and ol li strong to target these elements correctly. But this can be simplified to ul strong and ol strong since the ul and ol are specific enough:

      styles.css

      ...
      h3 strong {
        color: blue;
      }
      
      ul strong {
        color: dodgerblue;
      }
      
      ol strong {
        color: green;
      }
      

      Return to your browser and hit refresh. The <strong> element in the unordered list is now a rich light blue color and the <strong> element in the ordered list is now a green, as seen in the following image:

      Content of website in a black sans-serif font, with bold content in the secondary heading red, bold content in paragraph content light orange, content in the third-level heading blue, bold content in an unordered list a light blue, and bold content in an ordered list green.

      In this section, you learned about the combinator selector. You used the selector with two type selectors multiple times to create custom colors for various instances of <strong> elements. The next section will look at how to simplify your CSS by applying similar styles to multiple element types with the selector group.

      Selecting Multiple Elements With the Selector Group

      In this section, you will select HTML elements using a selector group. There is a principle of programming called Don’t Repeat Yourself, or DRY. The purpose of DRY code is to write code that is more maintainable. Using the selector group is one of the quickest ways to put the DRY principle in practice when writing CSS.

      Open up styles.css in your editor. Earlier in the tutorial you wrote out two styles to change a browser default weight from bold to normal:

      styles.css

      ...
      h2 {
        font-weight: normal;
      }
      
      h3 {
        font-weight: normal;
      }
      ...
      
      

      Since the h2 and h3 type selectors have the same property and value in the selector block, this can be consolidated with a selector group. A selector group is done by putting a comma between selectors. In this case, you can remove the h3 selector block, then add a comma then the h3 type selector after the h2 type selector. It can be helpful to put each selector on a new line to help legibility of the list.

      styles.css

      ...
      h2,
      h3 {
        font-weight: normal;
      }
      ...
      

      Open up the browser and reload index.html to verify nothing has changed. Both the h2 and the h3 now share the same styles thanks to the selector block. However, you are not limited to keeping the styles looking the same. You can still have individual h2 and h3 type selectors to provide specific styles to each element. Create each of these type selectors, then add a different color to each selector block:

      styles.css

      ...
      h2,
      h3 {
        font-weight: normal;
      }
      
      h2 {
        color: maroon;
      }
      
      h3 {
        color: navy
      }
      ...
      

      Refresh index.html in your browser to find that the h2 and h3 still have the same shared style of a normal font-weight, yet have their individual color properties.

      Selector groups are not limited to a particular kind of selector and can bring together various kinds of selectors to have the same style. This feature of grouping could be used in any number of ways. To bring in the selectors discussed already, add one of the combinator selectors to the h2, h3 selector group.

      styles.css

      ...
      h2,
      h3,
      ol strong {
        font-weight: normal;
      }
      ...
      

      After refreshing index.html in your browser, the <strong> element in the ordered list will no longer be bold and instead will have a normal font-weight, as in the following image:

      The <strong> text in the ordered list is still green, but now is no longer bold like the base <h2> and <h3> elements.

      Note With the selector group, you can bring different styles together into one selector block. But there is a balance to be struck between DRY CSS and human-readable CSS, with a best practice that errs on the side of human-readable. As an extreme example, it is possible to write several large group selectors so no single property is repeated, but that will be harder for developers to understand. In this case, developer readability is preferred.

      In this section, you worked with the group selector and turned repetitive CSS properties into a single selector block. You also added in a combinator selector with a selector group to write reusable properties with high specificity.

      Conclusion

      In this tutorial, you learned about the baseline selectors needed to write CSS. You can now effectively find an element on a page with CSS that is nested deep in HTML and give it specific styles. You also learned about the DRY programming principle, which is helpful to write concise and manageable CSS. These selectors can be paired with many other CSS selectors to get to the exact element and situation you wish to style.

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



      Source link