One place for hosting & domains

      CSS

      How To Style Figure and Image HTML Elements with CSS


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

      Introduction

      When styling images on a web page with CSS, there are many important ideas to keep in mind. By default, web browsers display images in a raw format at their default size. This can lead to images being larger than the rest of the content, or can introduce unexpected spacing problems for your page layout. This tutorial will lead you through examples of image styling for web pages, allowing you to make informed decisions about how images are displayed and altered to fit the context.

      In this tutorial, you will create a web page consisting of content and three images. The first image will be loaded as an <img /> element on its own, the second will be wrapped in the <figure> element with an appropriate <figcaption>, and the third will use the <picture> element to load different images at different screen sizes and use the object-fit and object-position properties to resize the image. You will also explore some of the fundamentals of responsive web design and ensure the accessibility of your images.

      Prerequisites

      Setting Up the Base HTML and CSS

      In this section, you will set up the base HTML for all the visual styles you will write throughout the tutorial. You will also create your styles.css file and add styles that set the layout of the content.

      Start by opening index.html in your text editor. Then, add the following HTML to the file:

      index.html

      <!doctype html>
      <html>
        <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <title>City Night</title>
          <link rel="preconnect" href="https://fonts.googleapis.com"> 
          <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> 
          <link href="https://fonts.googleapis.com/css2?family=Inconsolata:wght@300;400&display=swap" rel="stylesheet">
          <link rel="stylesheet" href="styles.css" />
        </head>
        <body>
        </body>
      </html>
      

      There are several page aspects defined inside the <head> element. The first <meta> element specifies the character set to use for the text. This way, special characters like accent marks will render without special HTML codes. The second <meta> element tells browsers (mobile browsers in particular) how to treat the width of the content; otherwise, the browser would simulate a 960px desktop width. Next, the <title> element provides the browser with the title of the page. The <link> elements load in the page styles. The first three load in the font, Inconsolata, from Google Fonts, and the last loads the styles you will write in this tutorial.

      Next, the page will need content to style. You will use sample content from Cupcake Ipsum as filler text to use with the styles. Throughout the tutorial, additions to code from previous steps will be highlighted. Return to index.html in your text editor and add the highlighted HTML from the following code block:

      index.html

      <!doctype html>
      <html>
        <head>
          ...
        </head>
        <body>
          <main>
            <h2>City Night</h2>
            <p> Candy bonbon carrot cake jelly beans shortbread fruitcake. Donut lollipop shortbread soufflé cotton candy cupcake cake. Pastry bear claw powder shortbread gingerbread.</p>
            <p>Caramels jelly-o marshmallow muffin macaroon bear claw candy canes gummies. Muffin shortbread sweet roll pastry marzipan pudding.</p>
            <p>Danish gummies oat cake marzipan shortbread pudding chocolate cake. Donut biscuit danish chocolate cake marzipan. Bonbon cheesecake gingerbread sesame snaps brownie ice cream caramels halvah.</p>
          </main>
        </body>
      </html>
      

      The <main> element contains the primary content of the page, with an <h2> text heading of City Night followed by three <p> elements of content. As you work through the tutorial, you will add images to the page between the content.

      Save your changes to index.html, then create a file in the same directory called styles.css. Open this file in your text editor. In your styles.css file, add the CSS from the following code block:

      styles.css

      body {
        margin: 0;
        font: 100% / 1.5 Inconsolata, monospace;
        color: hsl(230, 100%, 95%);
        background-color: hsl(230, 40%, 10%);
      }
      
      h2 {
        font-size: 3.5rem;
        font-weight: 300;
        text-shadow: 0 0 1em hsla(320, 100%, 50%, 0.5),
          0 0 0.125em hsla(320, 100%, 60%, 0.5),
          -0.25em -0.125em 0.125em hsla(40, 100%, 60%, 0.125),
          0.25em 0.125em 0.125em hsla(200, 100%, 60%, 0.25);
      }
      
      main {
        margin: 2rem auto 4rem;
        width: 90%;
        max-width: 70rem;
      }
      
      p {
        font-size: 1.25rem;
        max-width: 75ch;
      }
      

      These styles add the visual aesthetic and layout to the page. The body rule set adjusts the defaults to load the Inconsolata font, then changes the color to be light blue and the background color to a dark blue-purple. Next, the h2 header gets resized, uses a thinner font weight, and gains a unique effect with the use of the text-shadow property. The main element is set up to remain in the center of the page and stop growing in width once it reaches a size of 70rem, which is approximately 1120px. Lastly,the p selector sets the font-size a bit larger to 1.25rem and sets a separate max-width to 75ch, which is 75 characters at the current font-size.

      Save your changes to styles.css and then open your web browser. Select the File menu item, then select the Open option and load your index.html file in the browser. The following image demonstrates how this HTML will render in the browser:

      White monospace text on a dark blue purple background.

      In this section, you created the initial HTML and CSS for this tutorial. You loaded a custom font on the page and created a distinctive headline by using the text-shadow property. In the next section, you will add your first image to the page using the <img /> element, learn about its default browser styles, and set up the images on the page to be responsive.

      Setting Fluid Widths with the <img /> Element

      There are several things to be aware of when working with images on the web. First, images are by default shown on a page pixel for pixel. This means that if an image is 2048 pixels tall and wide it will occupy that much space on the browser, often causing horizontal and vertical scrolling. Next, images are considered inline flow content, which means images are treated like text in a browser and can be placed inline. This can be beneficial when wrapping text around an image with a float property, but otherwise it is best to separate images from text content to improve the final layout.

      To start working with images in your web page, create a new directory called images by running the following in your command prompt:

      Next, you will download a photo of a building with brightly colored doors by Luke Stackpoole. This image comes from the stock photography website Unsplash. Run the following curl command to download the photo into the new images directory:

      • curl -sL https://assets.digitalocean.com/articles/68128/night-doors.jpg -o images/night-doors.jpg

      Now that you have the image available on your computer to use, open index.html in your text editor. After the first paragraph in the content, add an <img /> self-closing element with a src attribute, as highlighted in the following code block:

      index.html

      ...
      <main>
        <h2>City Nights</h2>
        <p>Candy bonbon carrot cake jelly beans shortbread fruitcake. Donut lollipop shortbread soufflé cotton candy cupcake cake. Pastry bear claw powder shortbread gingerbread.</p>
        <img src="https://www.digitalocean.com/community/tutorials/images/night-doors.jpg" />
        ...
      </main>
      ...
      

      The src attribute directs the browser to the image you downloaded from Unsplash.

      A very important aspect of working with an image is to provide an alt attribute with a description of the image. This will help various users of your website know the image content, especially those using a screen reader. It is helpful to provide details around the context of the image, especially as it pertains to the rest of the text content. If an image is purely for decorative purposes, an alt attribute set to an empty string is acceptable, as otherwise a screen reader would read the file name.

      The highlighted HTML in the following code block provides a alt text description of this image:

      index.html

      ...
      <img src="https://www.digitalocean.com/community/tutorials/images/night-doors.jpg" alt="Three floors of several brightly-colored doors with a person walking on the second floor" />
      ...
      

      Save the addition of an image to index.html, then open the file in your web browser. The image will load between the first and second paragraph. Resizing the browser will have no effect on the image, as shown in the following animation:

      Animation of a page with an image causing a horizontal scrollbar to appear as the window width shrinks.

      As mentioned at the beginning of the section, images are shown at their native size, regardless of screen size. In order to make this image fit more screen sizes, you will next give the image fluid dimensions. Fluid image media is a key tenet of responsive web design, a method of web development that emphasizes code that adjusts to the constraints of the screen or browser size.

      In order to define fluid images, open styles.css in your text editor. Create an img element selector, then add a max-width property with a value of 100%, as highlighted in the following code block:

      styles.css

      ..
      p {
        font-size: 1.25rem;
        max-width: 75ch;
      }
      
      img {
        max-width: 100%;
      }
      

      The max-width property tells images they can scale down to fit a space. It also allows the image to grow until it hits the native pixel size. This different from using the width property set to 100%, which would allow the image to grow beyond the native size if the container were larger than the image. Additionally, the default behavior of a browser is to scale an image proportionally, so no height property is necessary.

      Save your changes to styles.css and then return to the browser and refresh index.html. Resize the browser so that the images scales down and back up until it reaches its full pixel size. The following animation depicts how this resizing interaction is rendered in a browser:

      Animation of a web page with an image, which shrinks as the window size shrinks.

      In this section you worked with the <img /> tag and successfully loaded an image on the page. You used the alt attribute on an image and applied a sufficient description of the image. Lastly, you tried out a way to resize all image to fit the space available. In the next section, you will use the <figure> and <figcaption> elements and change their default styling values.

      Providing Captions with <figure> and <figcaption>

      Often an image needs accompanying descriptive text to give the reader more context about the image, such as who is in the image or where the image is from. For this kind of situation, it is useful to place the <img /> inside a <figure> element with a <figcaption> element to hold the descriptive text. In this section, you will use these elements and adjust their default styles to overlay the text on a photo of a street in Tokyo by Jezael Melgoza.

      First, run this curl command in the following code block to download the image into the images directory:

      • curl -sL https://assets.digitalocean.com/articles/68128/tokyo-street.jpg -o images/tokyo-street.jpg

      Next, open index.html in your text editor. In between the second and third paragraphs, add a <figure> element. Within the <figure>, add a <img /> element with a src attribute pointing to the image you just downloaded. Then, add alt text that describes the contents of the photo. These updates are highlighted in the following code block:

      index.html

      ...
      <p>Caramels jelly-o marshmallow muffin macaroon bear claw candy canes gummies. Muffin shortbread sweet roll pastry marzipan pudding.</p>
      
      <figure>
        <img src="https://www.digitalocean.com/community/tutorials/images/tokyo-street.jpg" alt="A motion blurred street with an in-focus taxi." />
      </figure>
      
      <p>Danish gummies oat cake marzipan shortbread pudding chocolate cake. Donut biscuit danish chocolate cake marzipan. Bonbon cheesecake gingerbread sesame snaps brownie ice cream caramels halvah.</p>
      ...
      

      Save these updates, then return to your browser to load index.html. The image is displayed between the second and third paragraphs, but due to default styling has some inset spacing applied, as shown in the following image:

      White monospace text above and below an inset image of a taxi in Tokyo at night.

      The extra spacing of the <figure> is applied with the margin property on the left and right sides of the element. This is the default styling found on most browsers, which puts a 40px margin on the left and right and a 1em margin on the top and bottom.

      To adjust this default style, return to styles.css in your text editor. Create a new figure element selector and inside add a margin property set to 2rem 0, as highlighted in the following code block:

      styles.css

      ...
      img {
        max-with: 100%;
      }
      
      figure {
        margin: 2rem 0;
      }
      

      Setting the margin to 2rem 0 will apply 2rem spacing to the top and bottom of the figure and remove the spacing on the sides. This gives the image more space between the text, but allows it to occupy more space.

      Save your changes to styles.css and return to your browser to refresh the page. The following image shows how the figure spacing is now rendered:

      White monospace text above and below an image aligned to the text depicting a taxi in Tokyo at night.

      Next, to add a caption for the image, return to index.html in your text editor. Inside the <figure> element and beneath the <img /> element, add a <figcaption> tag. The highlighted HTML in the following code block demonstrates this setup with caption text:

      index.html

      ...
      <figure>
        <img src="https://www.digitalocean.com/community/tutorials/images/tokyo-street.jpg" alt="A motion blurred street with an in focus taxi." />
        <figcaption>Taxi in Tokyo, Japan</figcaption>
      </figure>
      ...
      

      The contents of a caption are useful to provide further information about the image that is not clearly evident. This is unlike the alt text, which describes in words the contents of the image. In this case, a useful caption is the location where the photo was taken.

      Due to the HTML order, the <figcaption> content will display below the image, but next you will style it so that it overlays the image with a dark gradient to help make the text legible.

      Return to styles.css in your text editor. In order to create an overlay, a position: relative property value will need to be added to the figure selector. Then, create a figcaption element selector and add the following highlighted CSS:

      styles.css

      ...
      figure {
        margin: 2rem 0;
        position: relative;
      }
      
      figcaption {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        padding: 5rem 1rem 1rem;
        background: linear-gradient(to top, hsla(230, 40%, 5%, 0.95), hsla(230, 40%, 5%, 0));
      }
      

      The figcaption styles set the container to overlay the bottom of the image with the position, bottom, right, and left properties. Next, the padding property is large on the top side with 5rem to give ample space for the gradient to spread above the text content, and the left, right, and bottom sides have a smaller 1rem spacing. Lastly, you create the gradient with the background property’s linear-gradient() value that transition’s a dark blue at 95% opacity up to the same color with 0% opacity. Together, this creates a shadowed edge at the bottom to contain the caption.

      Save your changes to styles.css and return to your browser to refresh the page. The gradient background of the <figcaption> shows up at the bottom of the image, but it overshoots the image on the bottom and right sides. The following image shows a close-up view of the difference between the image and the gradient:

      A misaligned dark blue gradient covering a photo on a dark blue-purple background.

      There are two different issues that cause this misalignment, which require two methods to adjust the styles and correct the issue.

      The first deals with how <img /> elements are treated as inline text by default. This extra space at the bottom is the line-height spacing that makes space between lines of text. There are two ways to adjust this, by either changing the line-height of the <figure> element or setting the <img> to have a display property set to block.

      The second issue is the difference in size between the image’s pixel-to-pixel dimensions and the max-width of the <main> element. Since the <figure> is a block element and the <figcaption> is set to span from the left edge to the right edge, it grows to fill a space larger than the image. The first way to fix this issue is to change the <img /> to have a width set to 100%. By setting this width the image will ignore the max-width: 100% default and instead fill the whole space. Note that this approach can cause image distortion depending on the difference in size. The second strategy to fix this is to change the <figure> to have a display property set to inline-block. This approach will cause the <figure> element’s size to shrink to fit its contents.

      Return to styles.css in the text editor and add the display approach for each issue. In the figure selector, add a display property set to a value of inline-block. Then, create a figure img descendant combinator selector with a display: block, as highlighted in the following code block:

      styles.css

      ...
      figure {
        margin: 2rem 0;
        position: relatve;
        display: inline-block;
      }
      
      figure img {
        display: block;
      }
      
      figcaption {
        ...
      }
      

      Save your changes to styles.css and then refresh index.html in the web browser. The <figure> shrinks down to the natural size of the image and the image is no longer treated as text. The following image shows how this adjustment to the display properties is rendered:

      White monospace text above and below an inset image of a taxi in Tokyo at night with a gradient and descriptive text overlaying the image.

      In this section, you used the <figure> and <figcaption> elements. You learned about the default styles of the <figure> and <img /> elements and how to change them for a more controlled outcome. Lastly, you created a caption that overlays the image with contextual information about the photo. In the last section, you will work with styling the <picture> element using the object-fit and object-position properties.

      Using Responsive Image Swapping with <picture>

      When working with images across various screen sizes, there are times when the image isn’t the right size and needs to adapt to the layout. The <picture> element exists to meet this need by defining different images to display at different screen sizes. The images can then be more tightly controlled with the object-fit and object-position properties, which set how an image scales between the specific sizes.

      To begin working with the <picture> element, you will need a series of different-sized images of the same source image. Use the following curl command to download a zip archive of three images of the same aerial photo of Tokyo by Pawel Nolbert:

      • curl -sL https://assets.digitalocean.com/articles/68128/picture.zip -o images/picture.zip

      Once the zip file finishes downloading, extract the content to your image folder. Run the following command in your prompt to place the files in the images directory:

      • unzip images/picture.zip -d ./images

      Now, open index.html in your text editor. First, you will create a <div> with a class attribute of hero between the opening <body> and <main> elements. Then add the remaining highlighted <picture> elements from the following code block:

      index.html

      ...
      <body>
        <div class="hero">
          <picture>
            <source  media="(min-width:70rem)" />
            <source  media="(min-width:40rem)" />
            <img class="hero-image" src="https://www.digitalocean.com/community/tutorials/images/tokyo-small.jpg" alt="Time-lapse exposure of a city at night." />
          </picture>
        </div>
        <main>
      ...
      

      The <picture> element requires a specific structure consisting of as many <source /> elements as needed and one <img /> element as the last item inside. All the accessibility and styling of the <picture> element comes from the <img /> element, which is why the <img /> has a class and the <picture> does not.

      The <img /> is the default image that is used to start when there are no media query requirements. The <source /> elements define two things: the location of the image file with the srcset attribute, and the screen size scenario with the media attribute. The browser will then access and load the appropriate image for the stated screen size, swapping out the image if the size changes.

      Save your changes to index.html, then open the file in your web browser. The following animation depicts the browser swapping the images as the window grows in size:

      Animation depicting an image changing to new cropped versions of the image as the window size increases.

      As the screen size changes, the image size changes as well, causing the text below to be pushed further down the page. In order to create a consistent spacing between this hero image area and the content, height properties can be set to maintain a consistent size.

      Return to styles.css in your text editor. At the bottom of the page, create a class selector for .hero. In the selector block, add the highlighted CSS from the following code block:

      styles.css

      ...
      .hero {
        height: 80vh;
        max-height: 40rem;
      }
      

      The height value set to 80vh means that the .hero container will at the least take up 80% of the browser’s screen height. Then the max-height property ensures that the .hero will not grow larger than 40rem, which is equivalent to 640 pixels tall.

      Save your changes to styles.css and refresh index.html in the browser. As the following animation illustrates, the text now maintains a consistent position. Meanwhile the visual distance between the image and content adjusts to the point that the image slides behind the text:

      Animation depicting shifting spacing between an image and the page content as the window size increases with the image and text, eventually overlapping.

      This overlap of the text and the image is a result of the browser erring on the side of content remaining visible, even if it goes beyond its ancestor’s container. A quick fix for this would be to apply an overflow: hidden on the .hero element, but that does not address the extra space when the image is scaled down smaller. To create a solution for both issues, the object-fit property can help by giving an image similar controls as a background image has with the background-size property.

      To begin working with object-fit, return to styles.css in your text editor. Since the <img /> element is the element that controls styling for a <picture> element, create a class selector for .hero-image and add the highlighted CSS from the following code block:

      styles.css

      ...
      .hero {
        height: 80vh;
        max-height: 40rem;
      }
      
      .hero-image {
        height: 100%;
        width: 100%;
        object-fit: cover;
      }
      

      In order to work with the object-fit property, the image needs to be able to grow both vertically and horizontally. By setting the height and width properties to 100%, you give the object-fit property full control of resizing the image. Without the object-fit property, the image would be squashed to fit the parent container. The cover value allows the image to be edge to edge either vertically or horizontally, depending on the orientation of the container. The object-fit property can accept the same values as the background-size property, including contain and dimension values.

      Save this new addition to styles.css and refresh index.html in your web browser. The following animation illustrates how the object-fit property allows the image to grow to fill the whole space of the .hero container and be hidden when it crosses the edge of the container, just like a background image:

      Animation depicting a defined spacing between image and text, where as the window size increases the image grows, and portions of the image are hidden as they grow beyond the bounds.

      Lastly, there is the object-position property. This works similarly to the background-position property to allow an image to be anchored to a specific area.

      Return to styles.css in your text editor and add an object-position property to the .hero-image selector. Set the value of the property to bottom right, which will anchor the image to the bottom right area as it resizes. The highlighted CSS in the following code block demonstrate how this is written:

      styles.css

      ...
      .hero-image {
        height: 100%;
        width: 100%;
        object-fit: cover;
        object-position: bottom right;
      }
      

      Save this change to styles.css, then return to your browser and refresh index.html.

      This time as the browser width changes and the image scales, the scaling stems from the center of the container, as shown in the following animation:

      Animation depicting a defined spacing between image and text, where as the window size increases the image grows, and portions of the image are hidden as they grow beyond the bounds, anchored at the bottom right of the image.

      This section introduced you to the <picture> media elements, the object-fit property, and the object-position property. You used this combination of elements and properties to create a resizing and adjusting large image at the top of the page.

      Conclusion

      With the techniques you practiced throughout this tutorial, you are now prepared to write styles that will format images to fit your design and layout. You created responsive images by setting a global max-width: 100% to all <img /> elements on the page. Next, you formatted an image caption to overlay the image and grow and shrink with the image. Then, you used the <picture> element along with the object-fit and object-position properties to swap and scale images to best fit the screen size. Using these strategies will help you solve more complex situations involving images and page layout.

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



      Source link

      How To Style Common Form Elements with CSS


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

      Introduction

      Web forms are a common element of website design, ranging in complexity from a search form field to contact forms and complex data filtering. Knowing how to use CSS to style and work with these elements helps provide better solutions to these everyday problems, and can improve your user’s experience of your website.

      This tutorial covers the creation and styling of a web form that requests various data from the user. The form will use text fields, radio buttons, checkboxes, drop-down selections, a text area, and submit and reset buttons. You will create and style this form and its elements
      by resetting the styles with the appearance property, setting up your own consistent style for the form, adding placeholder answers for the text fields, and customizing the radio buttons and checkboxes with various pseudo-classes and pseudo-elements.

      Prerequisites

      Setting Up the Base HTML and CSS

      In this first section, you will set up the HTML and initial styles that you will work with throughout the rest of the tutorial. This HTML will set up the scaffolding of the page and create the form fields you will style later.

      Begin by opening the index.html file in your editor. Then, add the following HTML to provide a base structure for the file:

      index.html

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

      The elements contained in the <head> element define the page’s name with the <title> element and where to load the stylesheet via the <link> element. The <meta> tags define the character encoding and instruct the browser on how to display the site on small-screen device. The main form contents will reside inside the <body> and <main> tags.

      Next, inside the <main> element, create a <form> element. Inside <form> you will add various form elements and <div> elements to help with layout. In this tutorial, additions to code from prior steps are highlighted. Add the highlighted HTML from the following code block to your index.html file:

      index.html

      ...
      <main>
        <form>
          <div>
            <label for="name">Name</label>
            <input id="name" type="text" />
          </div>
          <div>
            <label for="email">Email</label>
            <input id="email" type="email" />
          </div>
          <div>
            <label for="comp">Favorite CSS Compiler</label>
            <select id="comp">
              <option value="sass">Sass</option>
              <option value="less">Less</option>
              <option value="stylus">Stylus</option>
              <option value="postcss">PostCSS</option>
              <option value="other">Other</option>
            </select>
          </div>
          <div>
            <fieldset>
              <legend>Are you familiar with CSS Grid?</legend>
              <input type="radio" name="grid" id="yes" value="yes" />
              <label for="yes">Yes</label>
              <input type="radio" name="grid" id="no" value="no" />
              <label for="no">No</label>
            </fieldset>
          </div>
          <div class="full-width">
            <label for="message">Message</label>
            <textarea id="message"></textarea>
          </div>
          <div class="full-width">
            <input type="checkbox" id="newsletter" />
            <label for="newsletter">Receive our newsletter?</label>
          </div>
          <div class="full-width">
            <button type="submit">Send Response</button>
            <button type="reset">Clear Form</button>
          </div>
        </form>
      </main>
      ...
      

      HTML form structure consists of inter-connected attribute values in order to function correctly. This code creates a form that asks a user for their name and email, asks for their favorite CSS compiler and if they know CSS grid, provides a field for a user-generated message, and has a checkbox to sign the user up for a newsletter. To learn more about how to structure forms in HTML, see the Mozilla Web Docs page on web form structure.

      Be sure to save your changes to index.html, then create a new file in the same directory called styles.css.

      Open styles.css in your text editor. This file provides the styles that the browser will apply to the contents of index.html. Add the following CSS code to your styles.css file:

      styles.css

      body {
        margin: 0;
        background-color: hsl(0, 0%, 98%);
        color: #333;
        font: 100% / normal sans-serif;
      }
      
      main {
        margin: 0 auto;
        padding: 4rem 0;
        width: 90%;
        max-width: 60rem;
      }
      
      form {
        box-sizing: border-box;
        padding: 2rem;
        border-radius: 1rem;
        background-color: hsl(0, 0%, 100%);
        border: 4px solid hsl(0, 0%, 90%);
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 2rem;
      }
      
      .full-width {
        grid-column: span 2;
      }
      

      The body and the main element selectors create some initial text styling and layout for the overall page. The form element selector creates the styles for the overall form container and then defines a CSS Grid consisting of two columns of equal size with grid-template-columns: 1fr 1fr;. Then, the gap: 2rem provides 2rem spacing between each row and column in the grid. Lastly, the .full-width class selector allows containers with this class to extended between the two columns instead of staying in one column.

      Save your changes to styles.css. Next, open a web browser of your choice. Select the File menu item in the browser and then select the Open option. Next, navigate to your project folder and load your index.html file in the browser. The following image demonstrates how the page will render in the browser:

      Rounded white rectangle with a medium gray border on a light gray background. Several form field elements are in the white rectangle with black sans-serif labels.

      The form is displayed in a white box on a light gray background. Each form element is dispersed across the grid with the top four items alternating between the two columns and the last three stacked, spanning the two columns. The default styling of the form elements are as they appear in Firefox; each browser has a different default for styling form elements.

      In this section, you set up the initial HTML and CSS needed to work with form elements. You also learned that each browser handles the styling of these elements in a different way. In the next section, you will use the appearance property to equalize the styling of form elements across all browsers.

      Resetting Form Styling with the appearance Property

      Every browser handles the visual styling of form elements in a different manner. Often the styling of these elements goes beyond the initial capabilities of CSS and follows the aesthetic of the operating system or the browser’s own design language. In order to create consistent styling for all browsers, in this section you will use the appearance property and other properties to remove the default browser styles.

      To begin, open styles.css in your text editor. Create a new group selector consisting of button, fieldset, input, legend, select, and textarea. Then inside the selector block, add the appearance property set to none, as highlighted in the following code block:

      styles.css

      ...
      button,
      fieldset,
      input,
      legend,
      select,
      textarea {
        appearance: none;
      }
      

      The appearance property is the intended way to remove the special styling from form elements. However, due to the age and implementation of this property, most browsers still require a vendor prefix added to the property name. A vendor prefix is a special coded addition prepended to the property name as an identifier for a specific browser. For Chrome, Safari, and recent versions of Edge and Opera, that prefix is -webkit-. Firefox uses the -moz- prefix.

      When working with vendor prefixes, it is important to put the vendor prefix versions of a property first and end with the non-prefixed version. This way, older browsers that only support the prefixed property will use the prefix, but new browsers that support both prefix and the non-prefix versions will use the non-prefixed standard version. Add the highlighted prefix appearance properties as formatted in the following code block:

      styles.css

      legend,
      fieldset,
      select,
      textarea,
      input,
      button {
        -webkit-appearance: none;
        -moz-appearance: none;
        appearance: none;
      }
      

      Save your changes to styles.css and then open index.html in your browser. The appearance properties have removed the embellished styling and have gone to a simpler style, as rendered in the following image:

      Form elements with dark gray borders and middle gray borders creating depth effects.

      The appearance property only allows you to change the browser-specific styling. The biggest change the appearance: none property value made was to remove the radio buttons and checkbox completely. For the rest of the form elements, a few more properties are needed to completely remove the default styles. The highlighted CSS properties in the following code block add the necessary styles to remove the default styles:

      styles.css

      ...
      button,
      fieldset,
      input,
      legend,
      select,
      textarea {
        -webkit-appearance: none;
        -moz-appearance: none;
        appearance: none;
        background-color: transparent;
        border: none;
        padding: 0;
        margin: 0;
        box-sizing: border-box;
      }
      

      This CSS removes the background color and resets the parameters of the box model. Not all of these styles are necessary for all the elements, but it is acceptable to group these reset styles across all the elements.

      Save your changes to styles.css, then refresh index.html in the browser. The form elements have visually disappeared from the page, as shown in the following image:

      Black, sans-serif text in a white rectangle on a gray background.

      In this section, you used appearance and additional properties to completely remove the default styles from the form elements. You also used vendor prefixes to appropriately order apply the property for future browser versions. In the next section, you will begin customizing the visual styling of the form fields.

      Setting Consistent Styles Across Form Fields

      Now that the default browser styles have been completely removed, you will apply a consistent custom aesthetic across all the form elements. This will involve creating various group selectors that target specific form characteristics to receive the appropriate styles.

      To begin, open styles.css in your text editor. Then, create a group selector consisting of input, select, and textarea. Add the highlighted styles from the following code block:

      styles.css

      ...
      legend,
      fieldset,
      select,
      textarea,
      input,
      button {
        ...
      }
      
      input,
      select,
      textarea {
        border: 2px solid #333;
        background-color: white;
        border-radius: 0.25rem;
      }
      

      These styles add a 2px dark gray border around each of the data entry elements, along with a white background and rounded corners.

      Next, you will apply styles for the data entry elements that contain text inside. You will use an attribute selector to specify which input elements to target based on their type attribute value. The highlighted CSS in the following code block provide the styles for the necessary elements:

      styles.css

      ...
      input,
      textarea,
      select {
        ...
      }
      
      input[type="text"],
      input[type="email"],
      select,
      textarea {
        font: 1.25rem / 1.5 sans-serif;
        display: block;
        box-sizing: border-box;
        width: 100%;
        padding: 0.5rem 0.75rem;
      }
      

      These styles apply a consistent font size and family across all elements. The <textarea> element, for example, does not inherit the font settings from the body element. The display, box-sizing, width, and padding properties provide a consistent layout and structure for each of these data entry elements.

      Save your changes to styles.css and then open index.html in your web browser. As rendered in the following image, the fields now have a thicker dark gray border around them and the text of the <select> element is now much larger:

      Black, sans-serif text in a white rectangle on a gray background wth dark gray outline rectangles.

      Next, there are two elements that need some special styling in addition to the broad styling you’ve already written. The first is to give more height to the textarea, and the second is to apply a custom drop-down arrow to the <select> element.

      Return to styles.css and add a textarea element selector. Inside the selector block, create a min-height property set to a value of 10rem. This will create a larger initial area for the form user to fill in text. The highlighted CSS in the following code block illustrates how this is written:

      styles.css

      ...
      input[type="text"],
      input[type="email"],
      select,
      textarea {
        ...
      }
      
      textarea {
        min-height: 10rem;
      }
      

      After adding the styles for the textarea, the next thing to accomplish is to make an image directory. That can be done by running the following in your command prompt from within the same directory as your index.html and styles.css files:

      Next, run the following curl command to download the first image you will work with into the new images directory:

      • curl -sL https://assets.digitalocean.com/articles/68129/down-arrow.svg -o images/down-arrow.svg

      The image you downloaded is an SVG, which is a markup language similar to HTML with the purpose of drawing shapes.

      To add this new image to the <select> element, return to styles.css. Then, create a select element selector and add a background property with the highlighted value from the following code block:

      styles.css

      ...
      textarea {
        min-height: 10rem;
      }
      
      select {
        background: url("images/down-arrow.svg") no-repeat center right 0.75rem;
      }
      

      This background property loads the image into the <select> element’s background and does not repeat the image. Then it centers the image vertically with center and offsets it from the right side with right 0.75rem.

      Save your changes to styles.css, then return to your browser to refresh the page. The <textarea> is now about twice its original height and the <select> element has a blue downward-facing arrow on the right side. The following image illustrates how this is rendered in the browser:

      Black, sans-serif text in a white rectangle on a gray background with dark gray outline rectangles, one of which has a blue downward arrow.

      Throughout this section you created a custom aesthetic for the form’s data entry elements. You also created a background for the <select> element to replace the default arrow. In the next section, you will create custom radio buttons and checkboxes and apply selected states when they are checked.

      Customizing Radio Buttons and Checkboxes with the :checked Pseudo Class

      Now that you have created the base aesthetic of the form, it’s time to apply that visual style to the interactive input items of a radio button and checkbox.

      Start by opening styles.css in your text editor. You will change the input elements with a type attribute of radio or checkbox to have an equal height and width value. Then you will turn the radio buttons into circles. The highlighted portions of the following code block show how this is formatted:

      styles.css

      ...
      select {
        ...
      }
      
      input[type="radio"],
      input[type="checkbox"] {
        height: 1.5em;
        width: 1.5em;
        vertical-align: middle;
      }
      
      input[type="radio"] {
        border-radius: 50%;
      }
      

      The vertical-align property is meant for aligning inline text items. By setting this to middle, the input fields will sit in the middle of the text align. Then, the radio input with a border-radius property of 50% will create a circle because the height and width are the same.

      Save your changes to styles.css and then open index.html in your browser. The two radio buttons and the checkbox are now larger and more noticeable as rendered in the following image:

      Two circles with black sans-serif text and a rounded square with black sans-serif text.

      If you were to interact with the radio buttons or checkbox, nothing visible would happen. The appearance property also removes the selected indicators for these types of input. Next, you will use the :checked psuedo-class selector to apply styles to the selected input item.

      Return to styles.css and create a new selector for the radio button input with a :checked pseudo class. Then, inside the selector block, add a background-image with a radial-gradient so a filled-in style can be applied to selected radio buttons. The highlighted CSS from the following code block shows how this is formatted:

      styles.css

      ...
      input[type="radio"] {
        border-radius: 50%;
      }
      
      input[type="radio"]:checked {
        background-image: radial-gradient(
          hsl(213, 73%, 50%) 40%,
          transparent calc(40% + 1px)
        );
      }
      

      The calc() function allows the transparent property to be set 1px after the color value, creating a solid blue circle inside the input field.

      Save your changes to styles.css and return to index.html in your browser. The radio buttons now have a solid blue circle surrounded by white inside the input. The following image shows the Yes radio button selected:

      Two circles with black sans-serif text and a rounded square with black sans-serif text. One circle has a blue circle inside.

      Next, the checkbox will use a background image to indicate its :checked state, similar to the <select> dropdown’s arrow.

      Run the following curl command to download the checkmark image to your images directory:

      • curl -sL https://assets.digitalocean.com/articles/68129/check.svg -o images/check.svg

      Now that you have the image downloaded and ready to use, return to styles.css in your text editor.

      Next, add a input[type="checkbox"] selector with a :checked pseudo-class attached. In the selector block, add a background property that loads the check.svg image and scales it down to fit in the box. The highlighted CSS in the following code block indicates how this is written:

      stlyes.css

      ...
      input[type="radio"]:checked {
        ...
      }
      
      input[type="checkbox"]:checked {
        background: url('images/check.svg') no-repeat center / 75% auto;
      }
      

      The background property values ensure that the checkmark image is centered to the container, does not repeat, and is scaled down 75% proportionally.

      Save your changes to styles.css then refresh the page in the browser. When selecting the Receive our newsletter check box, now a checkmark appears inside, as illustrated in the following image:

      Square with rounded edge and a blue checkmark inside with black sans-serif text to the right.

      In this section, you created custom radio buttons and input fields and made them adjust their selected state through the use of the :checked pseudo-class. In the next section, you will style the <label> and <legend> elements on the page.

      Adding Special Styles to Labels and Legends

      The next elements to style are the <label> and <legend> elements in the form. There are two different styles that will be used: a small label style for the radio button and checkboxes and a large label style for the remaining elements.

      Open index.html in your text editor. You will add a class attribute to each <label> and <legend> with a value of either large-label or small-label, as highlighted in the following code block:

      index.html

      ...
      <form>
        <div>
          <label for="name" class="large-label">Name</label>
          <input id="name" type="text" />
        </div>
        <div>
          <label for="email" class="large-label">Email</label>
          <input id="email" type="email" />
        </div>
        <div>
          <label for="comp" class="large-label">Favorite CSS Compiler</label>
          ...
        </div>
        <div>
          <fieldset>
            <legend class="large-label">Are you familiar with CSS Grid?</legend>
            <input type="radio" name="grid" id="yes" value="yes" />
            <label for="yes" class="small-label">Yes</label>
            <input type="radio" name="grid" id="no" value="no" />
            <label for="no" class="small-label">No</label>
          </fieldset>
        </div>
        <div class="full-width">
          <label for="message" class="large-label">Message</label>
          <textarea id="message"></textarea>
        </div>
        <div class="full-width">
          <input type="checkbox" id="newsletter" />
          <label for="newsletter" class="small-label">Receive our newsletter?</label>
        </div>
        ...
      </form>
      ...
      

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

      In styles.css, add a .large-label class selector and add the following properties as highlighted in the following code block:

      styles.css

      ...
      .full-width {
        grid-column: span 2;
      }
      
      .large-label {
        display: inline-block;
        font: bold 1.5rem sans-serif;
        margin-bottom: 0.5rem;
      }
      ...
      

      These styles set the large-label elements to be large and bold with a font size of 1.5rem, which is equivalent to 24px. Then the margin-bottom property provides some space between the label and its counterparts.

      Save this change to styles.css and open index.html in your web browser. The label text above the data entry field will be large and bold, as rendered in the following image:

      Large, bold sans-serif text above black outline input fields.

      Return to styles.css and create another class selector for .small-label. Since these are the labels that are to the right of a radio button or checkbox, they will need some different spacing and sizing styles compared to the .large-label. Add the highlighted CSS to your styles.css from the following code block:

      styles.css

      ...
      .large-label {
        display: inline-block;
        font: bold 1.5rem sans-serif;
        margin-bottom: 0.5rem;
      }
      
      .small-label {
        vertical-align: middle;
        display: inline-block;
        margin-left: 0.25rem;
        margin-right: 1.5rem;
        font: 1.25rem sans-serif;
      }
      ...
      

      The vertical-align: middle will offset the text slightly. The font is set to 1.25rem, the equivalent of 20px, with sans-serif font. The margin properties on the left and right provide space between the input fields and the label.

      Save your updates to styles.css and refresh index.html in the browser. The labels next to the radio buttons and checkbox are now larger and provide more spacing, as rendered in the following image:

      Large, bold sans-serif text above black outline input fields with medium, thinner text.

      In this section, you created styles for two different types of labels based on where they were in relation to their input value. The labels now stand out, providing easier legibility and navigation throughout the form. In the next section, you will provide example data formatting through using the placeholder attribute.

      Providing Placeholder Content with the ::placeholder Pseudo-Element

      Placeholder content on an input or textarea element provides form users with a visual demonstration of what kind of information is being requested and how to format it. The placeholder attribute is added to the HTML with a value describing it. Then the ::placeholder pseudo-element allows for customizing the look of the text.

      To begin making placeholder content, open index.html in your text editor. Add a placeholder attribute to the name text <input />, the email <input />, and the <textarea> elements. The highlighted HTML in the following code block indicates where to add the placeholder and the value to use:

      index.html

      ...
      <form>
        <div>
          <label for="name" class="large-label">Name</label>
          <input id="name" type="text" placeholder="First or Full Name" />
        </div>
        <div>
          <label for="email" class="large-label">Email</label>
          <input id="email" type="email" placeholder="name@example.com" />
        </div>
        ...
        <div class="full-width">
          <label for="message" class="large-label">Message</label>
          <textarea id="message" placeholder="Leave a message…"></textarea>
        </div>
        ...
      </form>
      ...
      

      Save your changes to index.html, then open the page in a web browser. These three text entry areas now have content inside them. Once these text entry fields are selected and content is added, the placeholder text will be removed by the browser. The following image illustrates how the default placeholder styles appear in the browser:

      Black outline containers with light gray sample text inside.

      In order to style the placeholder, open styles.css in your text editor. Add a group selector for input::placeholder and textarea::placeholder. Be sure to use double colons between the selector and the pseudo-element, as this is how the browser recognizes the difference between a pseudo-class and a pseudo-element. The highlighted CSS in the following code block shows how this is written:

      styles.css

      ...
      textarea {
        min-height: 10rem;
      }
      
      input::placeholder,
      textarea::placeholder {
        opacity: 1; /* Firefox */
        color: hsl(213, 73%, 50%);
      }
      
      select {
        background: url("images/down-arrow.svg") no-repeat center right 0.75rem;
      }
      ...
      

      The one thing to note is that Firefox requires an opacity value set to 1 in order to have the full color value. Otherwise Firefox reduces the opacity, dimming the text color and causing accessible color contrast issues depending on the color value. Because this is a Firefox-only situation, a comment is there to explain the purpose of the opacity property’s presence.

      Save your changes to styles.css and return to the browser to refresh index.html. The placeholder text is now the same blue color used for the drop-down arrow and selected states for the radio button and checkbox. The following image illustrates how the browser renders the placeholder content:

      Black outline containers with blue sample text inside.

      With this section, you created placeholder content on text entry fields and styled them with the use of the ::placeholder pseudo-element. In the next section, you will create custom styles for form <button> elements.

      Creating Interactive Button Styles

      In web forms, <button> elements are often used to submit or reset a form. In index.html, there are two buttons, one with a type of submit and the other of reset. Both are functionally useful, but perform opposing actions. The submit button will send the form along to a processor, while the reset button clears all entered data from the form. Due to these different actions, the <button> elements need to look visibly different as well.

      To begin, open styles.css in your text editor and create a button element selector. In this selector block, you will add the styles that are shared between the submit and reset <button> elements, as highlighted in the following code block:

      styles.css

      ...
      input[type="checkbox"]:checked {
        background: url("images/check.svg") no-repeat center / 75% auto;
      }
      
      button {
        font: 1.25rem sans-serif;
        border-radius: 0.25rem;
        cursor: pointer;
        padding: 0.75rem 1.25rem;
      }
      

      The font sets both buttons to have the same font style and size. Then the border-radius adds a rounded corner to both buttons. The cursor property changes the style of the cursor to be the hand-style pointer. Lastly, the padding property defines the space around the inside of the button.

      Save your changes to styles.css and then open index.html in your web browser. The text in the button will grow and the spacing between the text will increase visually due to the padding. The following image shows how the buttons are rendered in the browser:

      Two phrases in dark gray on a white background.

      Next, return to styles.css to add styles for each button type by using an attribute selector targeting each. For the submit button, add a blue background-color and white text color. The reset button will gain a link-like underline and a margin to add more space between the buttons. Add the highlighted CSS from the following code block to your styles.css file:

      styles.css

      ...
      button {
        ...
      }
      
      button[type="submit"] {
        background-color: hsl(213, 73%, 50%);
        color: white;
      }
      
      button[type="reset"] {
        text-decoration: underline;
        margin-left: 1rem;
      }
      

      Save these additions to styles.css then refresh index.html in your text editor. The submit button is now a prominent blue and white, while the reset is subdued underlined text, as rendered in the following image:

      One phrase in white text in a blue container and another phrase in dark gray underlined text on white.

      The <button> element does not have a :hover state by default, so you will now add this to your style. A :hover state is useful to help cursor users have visual feedback that the cursor is situated on the buttons.

      To create :hover states for these <button> elements, return to styles.css in your text editor. Set the submit button’s backgound-color to darken on hover. Then, make the reset button drop the underline when hovered. The highlighted HTML in the following code block indicates how to write these styles:

      styles.css

      ...
      button[type="submit"] {
        background-color: hsl(213, 73%, 50%);
        color: white;
      }
      
      button[type="submit"]:hover {
        background-color: hsl(213, 73%, 40%);
      }
      
      button[type="reset"] {
        text-decoration: underline;
        margin-left: 1rem;
      }
      
      button[type="reset"]:hover {
        text-decoration: none;
      }
      

      Save your changes to styles.css and then return to the browser to refresh index.html. As the following animation portrays, the <button> elements shift their styles when the mouse cursor hovers over them:

      Animation of a blue button becoming darker on hover and underlined text losing the underline on hover.

      In this section, you created styles for the <button> elements so to make their differences visually noticeable. You changed how the cursor appears on hover by adjusting the cursor property. You also created custom styles to apply to each button to provide further visual feedback. In the last section, you will provide further visual activity feedback by creating styles when a form element is presently in use with the :focus pseudo-class.

      Clarifying the Active Form Fields With :focus

      When filling out a form, it is important for the user to know what field they are currently working on. You can accomplish this with the use of the :focus pseudo-class. By default, browsers employ an outline property to indicate when an element has :focus, but at times it may not be a noticeable indicator, or it may clash with other visual aspects of the design. In this section, you will create a custom :focus state that matches your form’s aesthetic.

      To begin working with form field :focus states, open styles.css in your text editor. Create a group selector for input, select, and textarea, all with a :focus pseudo-class, as highlighted in the following code block:

      styles.css

      ...
      input,
      select,
      textarea {
        ...
      }
      
      input:focus,
      select:focus,
      textarea:focus {
        outline: none;
        box-shadow: 0 0 0 4px hsl(213, 90%, 70%);
      }
      
      input[type="text"],
      input[type="email"],
      select,
      textarea {
        ...
      }
      ...
      

      These styles remove the browser default outline value and replace the style with a thick blue stroke created with the box-shadow property. The first three values of the box-shadow are for the shadow’s placement and blur amount. The fourth is called the spread, which in this case creates a 4px stroke around the focused element.

      Next, the buttons will receive a slightly different focus state, since the submit button is the same blue color. The purpose and intent of a focus state is to bring noticeable attention to the focused element, so you will distinguish these outlines in a different ways.

      Add a button:focus selector to styles.css. In the selector block, disable the outline default and add a box-shadow property. The placement, blur, and spread values will remain the same as the entry fields, but the color will be black instead of blue, as highlighted in the following code block:

      styles.css

      ...
      button {
        ...
      }
      
      button:focus {
        outline: none;
        box-shadow: 0 0 0 4px black;
      }
      
      button[type="submit"] {
        ...
      }
      ...
      

      Save your changes to styles.css and return to your browser. Refresh index.html and begin hitting the Tab key for the focus to shift between each element in the form. The following animation shows how the focus style is applied as the focus changes with the Tab key:

      Animation of form fields gaining a light blue outline sequentially.

      In this section, you created focus state styles that provide clear visual feedback when a form element has focus. This visual styling is helpful for mouse, touch, and keyboard input users.

      Conclusion

      Forms are a common element of web design. They allow users to interact with apps, search content, and provide feedback. In this tutorial, you created and styled a full-fledged form. You removed the browser default styles with the appearance property, and created a new custom aesthetic across various elements. You used the :checked pseudo-class to make selected states for radio buttons and checkboxes. Then you added placeholder content and matched the styling with the ::placeholder pseudo-element. After you created custom button styles, you applied :focus styles giving valuable visual interaction feedback to the form users.

      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 Use Opacity and Transparency to Create a Modal in CSS


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

      Introduction

      When styling HTML with CSS, there are multiple ways to adjust the opacity of elements, and multiple reasons to employ this effect in a design. Opacity can help soften a shadow, de-emphasize non-essential content during a specific task, or fade content in or out of view. You can accomplish these effects with the opacity property, the transparent color name, or alpha channels, which are an extension of color values with an additional segment for controlling opacity.

      Throughout this tutorial, you will use various ways to apply opacity and extra properties to effectively accomplish certain effects. You will create a modal that appears with a no-JavaScript approach using the :target pseudo class and the opacity, pointer-events, and transition properties. Then you will use each of the alpha channel color values to create shadow, border, and content overlays. You will also use the transparent color value to help make a gradient animate colors on a :hover event.

      Prerequisites

      • An understanding of CSS’s cascade and specificity features, which you can get by reading How To Apply CSS Styles to HTML with Cascade and Specificity.
      • Knowledge of type selectors, combinator selectors, and selector groups, which you can find in How To Select HTML Elements to Style with CSS.
      • An understanding of color properties. See How To Use Color Values with CSS to learn more about working with color in CSS.
      • Knowledge of CSS gradients with the background properties. Check out How To Apply Background Styles to HTML Elements with CSS to gain experience creating gradient backgrounds.
      • Experience with the box-shadow property, which you can learn more about in How To Style the Edges of HTML Elements with Borders, Shadows, and Outlines in CSS.
      • An empty HTML file saved on your local machine as index.html that you can access from your text editor and web browser of choice. To get started, check out our How To Set Up Your HTML Project tutorial, and follow How To Use and Understand HTML Elements for instructions on how to view your HTML in your browser. If you’re new to HTML, try out the whole How To Build a Website in HTML series.

      Setting Up the Base HTML and CSS

      In this first section, you will set up the HTML for the visual styles you will write throughout the tutorial. You will also create your styles.css file and add styles that set the layout of the content.

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

      index.html

      <!doctype html>
      <html>
        <head>
          <meta charset="utf-8" />
          <title>Destination: Moon</title>
          <link rel="preconnect" href="https://fonts.googleapis.com"> 
          <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> 
          <link href="https://fonts.googleapis.com/css2?family=MuseoModerno:wght@400;700&display=swap" rel="stylesheet">
          <link href="styles.css" rel="stylesheet" />
        </head>
        <body>
        </body>
      </html>
      

      Several page settings are defined inside the <head> element of the HTML. The <meta> element defines the character set to use for the text, which tells the browser how to interpret special characters in the code without using HTML character codes. The <title> element provides the browser with the title of the page. The <link> elements load in the page styles. The first three load in the font, Museo Moderno, from Google Fonts, and the last one loads the styles you will add to styles.css.

      Next, the page will need content to style. You will use sample content from Sagan Ipsum as filler copy to use with the styles. You will also apply HTML for a site header, containing the site name and a small navigation bar. Return to index.html in your text editor and add the highlighted HTML from the following code block:

      index.html

      <!doctype html>
      <html>
        <head>
          ...
        </head>
        <body>
          <header class="site-header">
            <h1 class="site-name">Destination: <strong>Moon</strong></h1>
            <nav>
              <ul class="nav-list">
                <li><a href="#" class="nav-link">Base Station</a></li>
                <li><a href="#" class="nav-link">Travel Packages</a></li>
                <li><a href="#" class="nav-link">Accommodations</a></li>
                <li><a href="#" class="nav-link">Plan Your Trip</a></li>
            </ul>
            </nav>
          </header>
          <main>
            <section>
              <h2>Schedule Your Trip</h2>
              <p>Sea of Tranquility great turbulent clouds with pretty stories for which there's little good evidence extraordinary claims require extraordinary evidence. Citizens of distant epochs rings of Uranus intelligent beings birth take root and flourish across the centuries. Corpus callosum invent the universe as a patch of light the only home we've ever known a mote of dust suspended in a sunbeam made in the interiors of collapsing stars. Kindling the energy hidden in matter Orion's sword.</p>
              <p>Vastness is bearable only through love emerged into consciousness not a sunrise but a galaxyrise emerged into consciousness courage of our questions across the centuries and billions upon billions upon billions upon billions upon billions upon billions upon billions.</p>
                <a href="#" class="button">Read the Disclaimer!</a>
            </section>
          </main>
        </body>
      </html>
      

      Be sure to save your index.html file and leave it open in your text editor. Next, create a new file called styles.css and open it in the text editor. This is the file that is referenced in the <head> element of index.html. In the styles.css file, add the following code:

      styles.css

      body {
        margin: 0;
        font: 100%/1.5 sans-serif;
      }
      
      main {
        margin: 6rem auto;
        width: 75ch;
        font-size: 1.125rem;
      }
      
      h2 {
        font: 400 1.875rem/1.25 MuseoModerno, sans-serif;
        color: #6b2d6b;
      }
      
      .site-header {
        font: 1.125rem / 1.25 MuseoModerno, sans-serif;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 2rem;
        color: white;
        background: linear-gradient(135deg, #8e3d8e, #230f23);
      }
      
      .site-name {
        margin: 0;
        font-size: 1.75rem;
        font-weight: 400;
      }
      
      .nav-list {
        margin: 0;
        padding: 0;
        list-style: none;
        display: flex;
        align-items: stretch;
      }
      
      .nav-link {
        color: inherit;
        display: block;
        text-decoration: none;
        padding: 1.25rem 1.5rem;
      }
      
      .nav-link:hover,
      .nav-link:focus {
        color: #230f23;
        background-color: white;
      }
      
      .button {
        text-decoration: none;
        display: inline-block;
        padding: 0.5rem 1.25rem;
        color: white;
        background: #4c90b2;
        border: 1px solid #2d566b;
        border-radius: 0.5rem;
      }
      
      .button:hover,
      .button:focus {
        background-color: #2d566b;
      }
      

      These styles set up the general aesthetic and layout of the page, with the styles applied to the body and main elements. The .site-header, .site-name, .nav-list, and .nav-link selectors all define the styles on the page header. The .button and .button:hover rules change an <a> element to appear like a large, clickable button.

      Save your changes to styles.css, then open a web browser. Select the File menu item and then select the Open option. Next, navigate to your project folder and load your index.html file in the browser. The following image demonstrates how the page will render in the browser:

      Sample website with a purple nav bar, a centered block of copy text, and a blue button with the words

      The CSS you have written so far creates a purple header at the top of the page with a site title and navigation in white text. Below, the content consists of a purple heading and two paragraphs of text. The width of the content is constrained to 75 characters with the max-width: 76ch property value on the main element selector. Lastly, the blue button with the text Read the Disclaimer! is a large, interactive element below the content.

      Throughout this section you set up your HTML in the index.html file and created the base styles in the styles.css file. In the next section, you will use the opacity property to cause a new element to disappear and reappear with the :target pseudo class.

      Creating :target State with opacity to Show and Hide Elements

      A useful application of the opacity property is to cause content to fade in and out on the screen. One instance of such an effect is when a modal, a UI element (also known as a light box) that appears in front of the rest of your page’s content, is transitioned into view. You can create this effect with a combination of the opacity and pointer-events properties and the :target pseudo-class.

      Start by opening index.html to create the contents of the modal. Add the highlighted HTML from the following code block between the </section> and </main> closing tags:

      index.html

      <!doctype html>
      <html>
        <head>
          ...
        </head>
        <body>
          ...
          <main>
            <section>
              ...
            </section>
            <div class="modal-container">
              <section class="modal">
                <header class="modal-header">
                  <h2 class="modal-title">Destination: Moon Disclaimer</h2>
                  <a href="#" class="modal-close">Close</a>
                </header>
                <div class="modal-content">
                  <p><strong>Disclaimer:</strong> Vastness is bearable only through love emerged into consciousness not a sunrise but a galaxyrise emerged into consciousness courage of our questions across the centuries and billions upon billions upon billions upon billions upon billions upon billions upon billions.</p>
                </div>
              </section>
            </div>
          </main>
        </body>
      </html>
      

      Save your changes to index.html, then return to styles.css in your text editor and append the highlighted CSS in the following code block to your file:

      styles.css

      ...
      
      .button:hover {
        background-color: #2d566b;
      }
      
      .modal-container {
        position: fixed;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        z-index: 1000;
        background-color: black;
        display: flex;
      }
      
      .modal {
        margin: auto;
        width: 90%;
        max-width: 40rem;
        background-color: white;
        border-radius: 1.5rem;
      }
      
      .modal-header,
      .modal-content {
        padding: 1.5rem;
      }
      

      The .modal-container class defines an area that will cover the full visible space with a fixed element. Then the display: flex on the .modal-container combined with the margin: auto on the .modal selector will center the content to the page both vertically and horizontally.

      Save your changes to styles.css and return to you browser to refresh index.html. The page’s contents are no longer visible as a black overlay has taken over the page with a white container, as rendered in the following image:

      White modal box with a black background covering the rest of the page

      Now that the modal is in place and covering the contents of the page, it needs to be hidden until instantiated. The opacity property is an older property that allows translucency to be placed on an element and its contents. The value of the opacity property can range from 0 to 1, with any decimal point between.

      To begin using the opacity property, return to styles.css in your text editor. On the .modal class selector, add an opacity property with a value of 0, as highlighted in the following code block:

      styles.css

      ...
      .modal-container {
         position: fixed;
         top: 0;
         right: 0;
         bottom: 0;
         left: 0;
         z-index: 1000;
         background-color: black;
         display: flex;
        opacity: 0;
      }
      ...
      

      This will cause the entire modal view to be visually hidden on the screen. The modal should only be visible when it needs to be. To achieve this conditional appearance, you can use the :target pseudo-class.

      After the .modal-container selector, add a new selector for .modal-container:target. Inside the selector block, set another opacity property to a value of 1. The highlighted CSS in the following code block shows how this is formatted:

      styles.css

      ...
      .modal-container {
        ...
        opacity: 0;
      }
      
      .modal-container:target {
        opacity: 1;
      }
      ...
      

      Save these changes to styles.css.

      The :target is instantiated when an element has a URL focus. In web browsers, the id attribute on an HTML element can be referenced in the URL as denoted by the pound or hash symbol (#). In order for the .modal-container:target to activate, the same element needs an id element, and the page needs a way to trigger that URL.

      Return to index.html in your text editor. On the <div class="modal-container"> element, add an id attribute set to the value disclaimer. Then, on the <a href="#" class="button"> element, change the href value from # to #disclaimer. Reference the highlighted HTML in the following code block for how this is written:

      index.html

      <!doctype html>
      <html>
        <head>
          ...
        </head>
        <body>
          ...
          <main>
            <section>
               ...
               <a href="https://www.digitalocean.com/community/tutorials/#disclaimer" class="button">Read the Disclaimer!</a>
             </section>
             <div id="disclaimer" class="modal-container">
               ...
             </div>
          </main>
        </body>
      </html>
      

      The change to the href value tells the browser to go to the element with the id value of disclaimer of the current page. Once the #disclaimer is added to the URL, then the :target in the CSS will activate.

      Save these changes to index.html, then return to styles.css.

      The way the page is structured now, the modal will capture all click and touch events coming from a mouse or touchscreen interaction. This is because, though completely transparent, the modal element is still covering the whole page. In order to remove interactivity from the element, you’ll add a pointer-events property with a value of none to the .modal-container selector. Then, once the modal is visible, it will need to be able to receive interaction events again. On the :target pseudo-class add pointer-events set to all, as highlighted in the following code block:

      styles.css

      ...
      .modal-container {
        ...
        opacity: 0;
        pointer-events: none;
      }
      
      .modal-container:target {
        opacity: 1;
        pointer-events: all;
      }
      ...
      

      The pointer-events property changes how an element interacts with a mouse or touch-based input device. By setting the value to none, the element becomes invisible not only to sighted users, but to pointer-based input devices as well. Then, the all value reinstates the interaction, but only when the .modal-container is specified in the URL to be active and visible.

      Lastly, to cause the modal to fade in and out of view, you’ll add a transition property to animate between 0 and 1 values for opacity.

      Return to styles.css and add a transition property to the .modal-container selector, as highlighted in the following code block:

      styles.css

      ...
      .modal-container {
        ...
        opacity: 0;
        pointer-events: none;
        transition: opacity 250ms ease;
      }
      
      .modal-container:target {
        opacity: 1;
        pointer-events: all;
      }
      ...
      

      The transition property is shorthand for a series of properties. The opacity tells the browser that this is the property to transition between. The 250ms is the time the transition should take to complete, with the unit standing for milliseconds. Finally, the ease describes how the transition will occur. In this case, ease means it will start slow, speed up, and then slow down again near the end of the transition.

      The transition will work when the modal appears and disappears by pressing the Close link inside the modal. This Close link has an href value set to #, which will change the URL from #disclaimer to #, removing the :target state.

      Save your changes to styles.css and refresh index.html in the browser. The following animation illustrates how the modal will appear and disappear:

      Animation of the modal appearing in a smooth transition, then disappearing with a smooth transition.

      This section introduced you to the opacity property, which you used to visually hide a modal container. You also used the :target pseudo-class, pointer-events property, and transition property to create a fade-in and fade-out effect. In the next section, you will use colors with alpha channels to make the modal more translucent.

      Using Alpha Channels to Create Transparent Color Values

      An alpha channel is like the opacity property, but instead is an additional segment for a color value defined via rgb(), hsl(), or hexadecimal. Where the opacity property adjusts the whole element and its children, the alpha channel only adjust the opacity of the color on a given property. Throughout this section, you will use each of the alpha channel color values and put them into practice.

      To begin working with alpha channel color values, open stlyes.css in your text editor. Then go to the .modal-container class selector. Change the background-color property’s value from #000 to rgba(0, 0, 0, 0.75), as highlighted in the following code block:

      styles.css

      ...
      .modal-container {
        ...
        background-color: rgba(0,0,0,0.75);
        ...
      }
      ...
      

      The rgba() color value works like the rgb(), containing three comma-separated numbers that indicate a level of red, green, and blue light. When one of the color values is set to 0, it is completely off (black), and 255 means it is at full brightness (white). Between these three color channels, millions of colors can be produced. The fourth number is the alpha channel, which works like the opacity property and is a decimal point value from 0 to 1. An adjustment to the alpha channel causes the color to become transparent, allowing the content behind it to become visible through the color.

      Save your changes to styles.css and open index.html in a web browser. Press the Read the Disclaimer! button so the modal activates. The black overlay background is still black, but is now also transparent, revealing the page behind it:

      The disclaimer modal, with the rest of the page visible behind a translucent black background.

      Now that the overlay is transparent, turn to the modal and give it more visual styling by changing the background to a purple gradient with white text. Return to styles.css in your text editor and add the following highlighted CSS from the next code block:

      styles.css

      ...
      .modal {
        margin: auto;
        width: 90%;
        max-width: 40rem;
        background: linear-gradient(135deg, hsl(300, 40%, 20%),hsl(300, 40%, 5%));
        border-radius: 1.5rem;
      }
      
      .modal-header,
      .modal-content {
        padding: 1.5rem;
      }
      
      .modal-header {
        display: flex;
        justify-content: space-between;
      }
      
      .modal-title {
        margin: 0;
        color: white;
      }
      
      .modal-close {
        color: white;
      }
      
      .modal-content {
        color: white;
      }
      
      

      Save this update to styles.css, then refresh index.html in your browser. The style of the modal will update and render as illustrated in the following image:

      The modal with a gradient background between purple and black and white lettering.

      Now, return to styles.css in your text editor. You will now use the hsla() color value to lighten the color of the modal header. You will also need to set the top corners to have a border-radius value that matches the modal, so the header doesn’t appear outside the modal area. The highlighted CSS in the following code block demonstrate how to set this up:

      styles.css

      ...
      .modal-header {
        display: flex;
        justify-content: space-between;
        background-color: hsla(300, 80%, 90%, 0.2);
        border-radius: 1.5rem 1.5rem 0 0;
      }
      ...
      

      The background-color value uses the hsla() format, and like the rgba() value, it is the hsl() format but with an alpha channel. The hsl() consists of three parts: a degree value from the color wheel, a saturation percent value, and a lightness percent value, which generates a final color. The 300 places the color value between blue and red on the color wheel, the 80% is a heavy saturation meaning more color and less gray, and the 90% lightens the final color. Lastly, the alpha channel works the same as the opacity property, and 0.2 sets the value closer to fully transparent. This will create a lightened overlay on top of the gradient, providing definition to the header.

      Save these changes to styles.css and return to the browser to refresh index.html. The header of the modal now has a pinker highlight to the area, distinguishing it from the content of the modal. The following image shows how the modal header is now rendered in the browser:

      Modal with header brightened to distinguish it from the modal content.

      Another way to create transparent color values is with hexadecimal values. Hexadecimal color values consist of three pairs of a combination of 0 to 9 or a to f and equate to a number ranging from 0 to 255. The first three digits are a red, green, and blue value, formatted as #RRGGBB. To create an alpha channel, a fourth set is added, making the pattern #RRGGBBAA.

      To begin working with hexadecimal alpha channels, return to styles.css in your text editor. You will now add a border to the modal’s header and content areas to give it more definition. These borders will use the same hexadecimal value, but will be given different values for the alpha channel. The highlighted CSS from the following code block shows how to write these styles:

      styles.css

      ...
      .modal-header {
        display: flex;
        justify-content: space-between;
        background-color: hsla(300, 80%, 90%, 0.2);
        border-radius: 1.5rem 1.5rem 0 0;
        border: 4px solid #f7baf72f;
        border-bottom: none;
      }
      ...
      .modal-content {
        color: white;
        border-radius: 0 0 1.5rem 1.5rem;
        border: 4px solid #f7baf744;
        border-top: none;
      }
      ...
      

      The header and the content each have the same hexadecimal color with #f7baf7, but they have different alpha channel values. The modal-header selector’s border-color has an alpha channel set to 2f, which is more transparent, since 00 is a fully transparent alpha channel value. The .modal-content has its alpha channel set to 44, which makes it more opaque.

      Save your changes to styles.css and refresh index.html in the web browser. The following image illustrates how these borders are rendered in the browser:

      Modal with added border around the modal container, rendered by adding transparency.

      Lastly, a six-digit hexadecimal color can be written as a three digit shorthand, where #33ccee is the same as #3ce. Likewise, a hexadecimal value with an alpha channel can be written as a four digit shorthand so that #33ccee99 can be shortened to #3ce9 and be the same color.

      To begin working with a shorthand hexadecimal with alpha channel, return to stlyes.css in your text editor. Then, go to the .modal class selector and add a box-shadow property. Here you will create a large drop shadow on the modal, which will be black but softened by an alpha channel. Add the highlighted CSS in the following code block to your .modal selector block:

      styles.css

      ...
      .modal {
        margin: auto;
        width: 90%;
        max-width: 40rem;
        background: linear-gradient(135deg, hsl(300, 40%, 20%),hsl(300, 40%, 5%));
        border-radius: 1.5rem;
        box-shadow: 0 1rem 2rem #000a;
      }
      ...
      

      This shadow drops down the x-axis by 1rem and spreads out the blur 2rem. Next, the #000a value defines a full black color by turning off all three color values. The a, which is equivalent to aa and has a numerical value of 170, provides the alpha channel with approximately a 66% transparency. This dims the shadow slightly but keeps it substantial enough to provide depth below the modal.

      Be sure to save this addition to styles.css, then refresh index.html in the browser. The modal now has much more definition and depth. The following image provides a rendering of the modal with the various color values:

      Modal with added shadow to make it look like it is floating above the page content.

      In this section, you used the three different color values with alpha channels to apply opacity to colors on specific properties. You added these colors to background-color properties, border properties, and a box-shadow property. In the next section, you will use the named color value of transparent to create unique gradients and hide content.

      Adding the transparent Color Value to a linear-gradient

      The various color values that support alpha channels are helpful for when a color still needs to be identifiable. However, when no color is needed, the transparent named color becomes useful. In this section, you will hide the Close button in the modal and create an X shape with a linear-gradient(), all with the use of the transparent value.

      To start using the transparent value, open styles.css in your text editor. Then, go to the .modal-close class selector that you added earlier. Inside the selector, change the color property value from white to transparent, as highlighted in the following code block:

      styles.css

      ...
      .modal-close {
        color: transparent;
      }
      ...
      

      This change will not remove the text from the space; it will only remove it from visually rendering on the page.

      Next, you will create a square out of the close link so there is a place to create the X shape. Start by adding a display property set to block, which allows the <a> to be more visually configurable. Next, create a height and width property and set each to 1.5rem, which creates the square shape. Finally, add an overflow property set to hidden, which will prevent text from going outside the container and adding interactive space. The highlighted CSS from the following code block shows how to set up the square:

      styles.css

      ...
      .modal-close {
        color: transparent;
        display: block;
        height: 1.5rem;
        width: 1.5rem;
        overflow: hidden;
      }
      ...
      

      The last part is to create the X shape with a multiple-background instance consisting of two linear-gradient() values. To set this up, add the highlighted code from the following code block:

      styles.css

      ...
      .modal-close {
        color: transparent;
        display: block;
        height: 1.5rem;
        width: 1.5rem;
        overflow: hidden;
        background-image:
          linear-gradient(
            to top right,
            transparent 48%,
            white 48%,
            white 52%,
            transparent 52%
          ),
          linear-gradient(
            to top left,
            transparent 48%,
            white 48%,
            white 52%,
            transparent 52%
          );
      }
      ...
      

      The first thing to note about this code is that the different segments of the linear-gradient() are on separate lines, which is done to help make the complex background more comprehensible and legible. This CSS is still valid, and it is not required that values are on the same line as the property. Next, the duplicated percent values for transparent and white mean there will be no gradation. Instead the color will flip immediately from transparent to white. Lastly, the to the right and to the top makes two gradients on 45 degree angles that overlap.

      Save this change to styles.css and open index.html in a web browser. Select the Read the Disclaimer! button and the modal will now have a large, thin X shape instead of a close link, as rendered in the following image:

      Modal box with the 'Close' button replaced with a thin white X.

      Lastly, a :hover and :focus state is needed to help make the X shape more noticeable when it is the center of interaction. For this, you will duplicate the previous gradients and adjust the position to grow the solid white area.

      To create an interactive state for the X, return to styles.css in your text editor. Following the .modal-close class selector, create a new group selector consisting of .modal-close:hover and .modal-close:focus. Then, duplicate the background-image property and value from .modal-close into the new selector. Lastly, decrease the 48% segments to 46% and increase the 52% to 54%.

      style.css

      ...
      .modal-close {
        ...
      }
      
      .modal-close:hover,
      .modal-close:focus {
        background-image:
          linear-gradient(
            to top right,
            transparent 46%,
            white 46%,
            white 54%,
            transparent 54%
          ),
          linear-gradient(
            to top left,
            transparent 46%,
            white 46%,
            white 54%,
            transparent 54%
          );
      }
      ...
      

      Save these changes to styles.css and refresh the page in your browser. Now, as the X is hovered over or given keyboard focus, the size of the gradients creating the shape will increase, giving an effect as though the X is bolded. The following animation demonstrates how this effect is rendered in a browser during a hover event:

      Animation of the cursor hovering over the X button. The lines of the X become visibly wider.

      This section introduced you to the transparent property, and you used it to hide content and create an X icon using linear-gradient() values. In the last section, you will use the transparent value on a gradient to help provide an animation effect on a button-styled element.

      Using the :hover State to Transition Between Transparent color Values

      One aspect of the transition property that sometimes requires creative solutions is that not all properties can be animated. One of these properties is the background-image, meaning the values of a linear-gradient on this property cannot animate. However, the background-color value can animate even if a background-image is present. In this section, you will create a transition animation that appears to be a gradient animation with the use of transparent and alpha channel color values.

      To create an animated gradient, open styles.css in your text editor. Then go to the .button class selector. The .button class already has a change in the background-color between its selector and the .button:hover. Add the highlighted transition property and value from the following code block to your styles.css file:

      styles.css

      ...
      .button { 
        text-decoration: none;
        display: inline-block;
        padding: 0.5rem 1.25rem;
        color: white;
        background: #4c90b2;
        border: 1px solid #2d566b;
        border-radius: 0.5rem;
        transition: background-color 250ms ease;
      }
      
      .button:hover,
      .button:focus {
        background-color: #2d566b;
      }
      ...
      

      Save your changes to styles.css and open index.html in you web browser. Hovering the button with a cursor will now cause the background-color to animate between light blue and dark blue. The following animation shows how this is rendered in the browser:

      An animation of the cursor hovering over the

      Now, to add the gradient, go back to styles.css in your text editor. Return to the .button selector and add a background-image property with a linear-gradient(). The direction of the gradient will be to bottom and will start with an alpha channel light blue then go to transparent. The animation will end with an alpha channel dark blue. The highlighted CSS in the following code block demonstrates how to write this gradient:

      styles.css

      ...
      .button { 
        text-decoration: none;
        display: inline-block;
        padding: 0.5rem 1.25rem;
        color: white;
        background: #4c90b2;
        border: 1px solid #2d566b;
        border-radius: 0.5rem;
        background-image:
          linear-gradient(
            to bottom,
            hsla(200, 40%, 80%, 0.4),
            transparent,
            hsla(200, 40%, 20%, 0.6)
          );
        transition: background-color 250ms ease;
      }
      ...
      

      This gradient overlays the background-color, giving the appearance that the gradient is passing from a light blue to a middle blue and then a dark blue. When the button encounters an interactive event, the background-color changes to a darker blue, creating an illusion that the overall gradient darkened.

      Save these updates to styles.css and then return to your index.html file in the browser and refresh the page. As shown in the following animation, as the cursor hovers the button the gradient appears to animate from a light blue gradient to a dark blue gradient:

      An animation of the cursor hovering over the

      In this last section, you used color values, the transparent named value, and the transition property to create an illusion of a gradient animating. Due to this, you also learned what kinds of properties can be animated.

      Conclusion

      Throughout this tutorial, you used the opacity property and many color values with alpha channels. You used opacity with pointer-events and transition to create a fade-in effect to display a modal on demand. You also used the various color values available to control the transparency and overlay of color on the content. You used the transparent named value to create an X icon to close the modal. Finally, you used a combination of colors, transparent value, gradients, and transition to create the illusion of an animated gradient on a button.

      There are many useful reasons to employ opacity and transparent colors to a web design. The opacity property can be used to animate a fade-in and fade-out effect on elements that are meant to be visible when needed. The various color values that allow for transparency control provide many ways to blend colors and content together. Altogether, these methods of creating transparency can create many unique effects and styles.

      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