One place for hosting & domains

      Image

      How to Create the Perfect WordPress Featured Image (Sizing & Design Guide)


      To draw new visitors to your site, you may consider publishing blog posts regularly. However, without featured images, your posts likely won’t look inviting enough to earn clicks.

      Fortunately, you can easily create well-designed featured images for your articles. Once you know how to find the right photos, size them correctly, and optimize them for search engines, you can instantly revitalize your WordPress posts.

      In this post, we’ll explain what a featured image is. Then, we’ll share some tips on how to use them. Let’s get started!

      What is a Featured Image?

      In WordPress, the featured image is the visual representation of a specific post, page, or custom post type. When someone visits your website, these images will usually appear at the top of posts or in your blog feed:

      WordPress featured images

      Essentially, the featured image is the default thumbnail of your post. If someone shares the post on social media, this image will appear with the link:

      Social media featured image

      In WordPress, the featured image settings are determined by your theme. This includes the location and size of your images.

      Typically, featured images are displayed in the following places:

      • The top area of posts or pages
      • Pages on your website that link to blog posts, like your WordPress homepage, recommended posts section, or search results
      • Thumbnails for social media links

      Sometimes, featured images may be included in image galleries or sliders. You may also see them as background images.

      The Advantages of Using Featured Images

      If you’re new to WordPress, you might be wondering why you need a featured image for every post on your website. However, these can be the key to making a good first impression with new visitors.

      After users click on a link to one of your posts, featured images are often the first thing they’ll see and this can engage them enough to continue reading the article:

      Post featured image

      You’ll likely have a list of your published posts on your homepage. You can motivate visitors to read your content by including well-designed featured images.

      Plus, having a featured image for each post can help you establish visual consistency on your website:

      Home page featured images

      When you share your posts on social media, featured images can help advertise your content to users browsing their feeds. A well-designed image can increase engagement and generate more clicks to your site.

      What is the Ideal WordPress Featured Image Size?

      As we mentioned earlier, different WordPress themes can have various sizes for featured images. However, the general size is 1200 x 628 pixels.

      Here’s how this would look with the default Twenty Twenty-Two theme:

      Featured image size

      This size will work effectively with many WordPress themes. However, your featured image sizing may vary based on your personal preference and the layout of your theme.

      It’s important to note that WordPress will resize your images to its default settings. Whenever you upload an image, it creates three different versions:

      • Thumbnail: 150 x 150 px
      • Medium: 300 x 300 px
      • Large: 1024 x 1024 px

      If you want to keep the original size of the featured image, this will be its ‘Full Size.’ To edit any of these sizing options, you can navigate to Settings > Media:

      WordPress media settings

      Here, you can update the width and height with new values. Once you save your changes, uploaded images will resize to these dimensions.

      You can also add a custom featured image size. Before you do so, it’s a good idea to back up your website. After this step, you can add the following code to your functions.php file:

      add_image_size( string $name, int $width, int $height, bool|array $crop = false )

      Make sure to update these values with your new featured image sizes. Here’s an example of how this might look:

      add_image_size( 'post-thumbnail size', 800, 1500 );

      Next, you’ll need to display the new size within your theme. In your theme template file, update the_post_thumbnail() function:

      if ( has_post_thumbnail() ) {
      the_post_thumbnail( 'your-custom-size' );
      }

      Once you save the file, you’ll have a new custom-featured image!

      Get Content Delivered Straight to Your Inbox

      Subscribe to our blog and receive great content just like this delivered straight to your inbox.

      How to Set a Featured Image in WordPress

      To set a featured image, open your WordPress dashboard and create a new post. Then, in the right-hand sidebar, look for the Featured Image section:

      Add WordPress featured image

      Here, click on Set Featured Image. This will open a pop-up where you can upload your media file. Alternatively, you can select an image from your Media Library:

      Select featured image

      If you need to adjust the size, find the Edit Image button. Then, use the various editing options to scale, crop, rotate, or flip the image as needed:

      Edit featured image

      When you’re done, hit Set featured image. You’ll now see a preview of the image while you create the post:

      New WordPress featured image

      Before you publish the post, you’ll want to preview it to ensure the featured image is showing. Remember that your theme may require more specific dimensions to work correctly. You can refer to your theme’s documentation if you experience difficulties during this process.

      Additionally, you can install a few plugins to make this process easier. For example, Auto Featured Image will automatically use the first photo in your post as the featured image. You can also use Default featured image to select a picture that will be used as a featured image in case you forget to add one to a post.

      How to Create the Perfect WordPress Featured Image (6 Tips)

      Featured images can turn your website into an engaging, media-rich experience. Let’s discuss some best practices for creating them!

      1. Be Relevant and Consistent

      When used correctly, featured images can enhance your blog posts and make them more attractive to visitors, but there are a few things you’ll need to keep in mind.

      First, you’ll want to avoid using random images. A featured image should serve as an introduction to a post, so it needs to be relevant to the content.

      For example, if you run a food blog, you probably publish posts with new recipes. In this case, your featured image can be a photo of the finished meal:

      Relevant featured image

      It’s also good practice to keep your featured images consistent throughout your entire website. Since these will be displayed on your homepage, archive, and blog, you’ll want photos that align with your web design:

      Consistent featured images

      To find the right featured image, consider your current WordPress theme and layout. Then, select a high-resolution image that can be easily scaled down. After you finish creating the post, make sure to preview it to evaluate how well the image fits into your website.

      2. Avoid Using Copyrighted Images

      As you’re browsing images on the Internet, you may stumble across a photo that would look great as a featured image. However, before you upload it to your WordPress site, you’ll need to ensure that it isn’t copyrighted to avoid legal issues.

      When sourcing images, you can typically use anything under a Creative Commons license. These will be free to download and use on your website, except if they’re for commercial purposes.

      To find Creative Commons images, open Google Images. Then, click on Tools > Usage Rights > Creative Commons licenses. Once you refine your search, you’ll get a wealth of free images to choose from:

      Creative commons images

      There are also entire websites with these stock images. On a platform like Unsplash, you can download high-resolution photos that are free from copyright claims:

      Unsplash website

      Another alternative is to make your own featured images. By taking photos yourself or creating graphics in Canva, you can ensure that you avoid any copyright violations. Plus, these will be completely original!

      3. Optimize Featured Images to Reduce File Size

      If you publish posts on a regular basis, featured images will start taking up a lot of space in your Media Library. If they aren’t optimized properly, these photos could negatively affect your site performance.

      Essentially, optimizing your images involves reducing their file sizes. By compressing your featured images, you can minimize your loading time.

      If you don’t do this, you could end up with a poor Core Web Vitals score. Images might take too long to render, and you’ll see performance issues in your PageSpeed Insights reports:

      Failed Core Web Vitals report

       

      Fortunately, there’s an easy solution for this common image issue. A plugin like TinyPNG can automatically compress images as you upload them:

      TinyPNG plugin

      Plus, you’ll even be able to compress all images that you’ve already uploaded to your website. TinyPNG lets you bulk optimize any JPEG, PNG, or WebP images in your Media Library.

      4. Regenerate Old Thumbnails

      When you upload images to WordPress, it will resize them according to the pixel guidelines in your settings. Once you set new default sizes, your previously uploaded images will still have the outdated sizing.

      If you want to resize your featured images, you can manually reupload them. However, this will take some time.

      To solve this problem, you can install a WordPress plugin like reGenerate Thumbnails Advanced. This tool can regenerate the thumbnails for each of the images in your Media Library:

      Regenerate Thumbnails Advanced plugin

      After you install and activate the plugin, go to Tools > Regenerate Thumbnails. Under Regenerate Options, select the box next to Regenerate only Featured Images:

      Regenerate featured images

      Finally, hit Regenerate. This will automatically update all your featured images with the correct sizing.

      5. Optimize Images for Search Engines

      As a website owner, you probably already know how vitally important Search Engine Optimization (SEO) is. If you want to avoid paying for expensive advertising methods, you’ll want to rise to the top of search results by optimizing your content. This can help you bring in more organic traffic.

      Having featured images can help you improve your site’s SEO. By simply tweaking a few elements, you can make your images more appealing to search engines and users.

      First, you’ll want to make sure to add alt text. This will describe the featured image to search engines and screen readers. For instance, you could write “Orange and white cat standing in a pumpkin patch”:

      Featured image alt text

      Remember to include the post’s keyword in the alt text. This way, Google can understand what the post is about and rank it higher for related queries. Similarly, you can include these target keywords in the title, caption, and description for the featured image.

      6. Enhance Social Post Thumbnails

      Social media can be the perfect platform for promoting your blog posts. Before you encourage social sharing, it’s crucial to optimize your featured images for these platforms.

      You can easily customize your social media links using a plugin like Yoast SEO. For example, the premium version enables you to see previews of your Twitter and Facebook thumbnails.

      To get started, install and activate Yoast SEO. Next, find Yoast SEO > Social. On this page, fill out the URLs for your various social media pages:

      Add social media accounts

      Then, open a new post and scroll down to the Yoast SEO settings. In the Social tab, you can click on Select image to upload your featured image.

      Featured image for social posts

      You can also add a title and description for each social media platform. This will give visitors a taste of your content. Once you publish the post on social media, it will have a featured image and snippet that conveys precisely what the article is about.

      Use Featured Images Effectively

      Featured images can help make your posts stand out. Whether people are browsing your content on social media or your website, they can look at the featured image to see what the post is about before they start reading it.

      To review, here’s how you can create the perfect WordPress featured image:

      1. Be relevant and consistent.
      2. Find copyright-free images on platforms like Unsplash.
      3. Compress featured images with TinyPNG.
      4. Regenerate old thumbnails with reGenerate Thumbnails Advanced.
      5. Optimize images for search engines using keyword-focused alt text.
      6. Enhance social post thumbnails with Yoast SEO’s social settings.

      When you create your own featured images, you can build an original website without facing copyright issues. At DreamHost, our custom website design services can help you use the right images on your site.

      DreamHost Makes Web Design Easy

      Our designers can create a gorgeous website from SCRATCH to perfectly match your brand and vision — all coded with WordPress so you can manage your content going forward.

      custom website design



      Source link

      How to Deploy a Packer Image with Terraform


      Both the Packer and Terraform tools by HashiCorp stand out for remarkable infrastructure-automating. Despite some overlap, the tools have distinct and complimentary features. This makes them an effective pair, with Packer used to create images that Terraform then deploys as a complete infrastructure.

      Learn more about Packer in our
      Using the Linode Packer Builder to Create Custom Images guide. Discover how you can leverage Terraform in our
      Beginner’s Guide to Terraform.

      In this tutorial, find out how to use Packer and Terraform together to deploy Linode instances. The tutorial uses the Linode Terraform provider to deploy several instances based on a Linode image built with Packer.

      Before You Begin

      1. If you have not already done so, create a Linode account and Compute Instance. See our
        Getting Started with Linode and
        Creating a Compute Instance guides.

      2. Follow our
        Setting Up and Securing a Compute Instance guide to update your system. You may also wish to set the timezone, configure your hostname, create a limited user account, and harden SSH access.

      Note

      This guide is written for a non-root user. Commands that require elevated privileges are prefixed with sudo. If you’re not familiar with the sudo command, see the
      Users and Groups guide.

      How to Install the Prerequisites

      To get started, install both Packer and Terraform on the same system. Below you can find links to installation guides for the two tools, as well as steps covering most Linux operating systems.

      Installing Packer

      Packer’s installation process varies substantially depending on your operating system. Refer to the
      official installation guide for instructions if your system is not covered here.

      Debian / Ubuntu

      sudo apt-get update && sudo apt-get install -y gnupg software-properties-common
      curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo apt-key add -\
      sudo apt-add-repository "deb [arch=amd64] https://apt.releases.hashicorp.com $(lsb_release -cs) main"
      sudo apt-get update && sudo apt-get install packer

      AlmaLinux / CentOS Stream / Rocky Linux

      sudo yum install -y yum-utils
      sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
      sudo yum -y install packer

      Fedora

      sudo dnf install -y dnf-plugins-core
      sudo dnf config-manager --add-repo https://rpm.releases.hashicorp.com/fedora/hashicorp.repo
      sudo dnf -y install packer

      Afterward, verify your installation and display the installed version with the following command:

      1.8.4

      Installing Terraform

      Terraform’s installation process also varies depending on your operating system. Refer to HashiCorp’s
      official documentation on installing the Terraform CLI for systems that are not covered here. You can also refer to the section on installing Terraform in our guide
      Use Terraform to Provision Linode Environments.

      Debian / Ubuntu

      sudo apt-get update && sudo apt-get install -y gnupg software-properties-common
      wget -O- https://apt.releases.hashicorp.com/gpg | gpg --dearmor | sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg
      echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
      sudo apt update && sudo apt install terraform

      AlmaLinux / CentOS Stream / Rocky Linux

      sudo yum install -y yum-utils
      sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
      sudo yum -y install terraform

      Fedora

      sudo dnf install -y dnf-plugins-core
      sudo dnf config-manager --add-repo https://rpm.releases.hashicorp.com/fedora/hashicorp.repo
      sudo dnf -y install terraform

      Afterward, verify your installation with:

      Terraform v1.3.3
      on linux_amd64

      How to Build a Packer Image

      Packer automates the creation of machine images. These images are helpful when looking to streamline your process for provisioning infrastructure. Such images give you a consistent basis for deploying instances.

      Moreover, images are much more efficient. Rather than executing a series of installations and commands with each provisioned instance, the provisioning tool can deploy ready-made images.

      The examples in this tutorial uses a Linode image built with Packer. Linode has a builder available for Packer, which lets you put together images specifically for a Linode instance.

      To do so, follow along with our guide on
      Using the Linode Packer Builder to Create Custom Images. By the end, you should have a Packer-built image on your Linode account.

      The remaining steps in this tutorial should work no matter what kind of image you built following the guide linked above. However, the Packer image used in the examples to follow has the label packer-linode-image-1, runs on an Ubuntu 20.04 base, and has NGINX installed.

      How to Configure Terraform

      Terraform focuses on automating the provisioning process, allowing you to deploy your infrastructure entirely from code.

      To learn more about deploying Linode instances with Terraform, see our tutorial on how to
      Use Terraform to Provision Linode Environments.

      This tutorial covers a similar series of steps, but specifically demonstrates how you can work with custom Linode images.

      Before moving ahead, create a directory for your Terraform scripts, and change that to your working directory. This tutorial uses the linode-terraform directory in the current user’s home directory:

      mkdir ~/linode-terraform
      cd ~/linode-terraform

      The rest of the tutorial assumes you are working out of this directory.

      Setting Up the Linode Provider

      Terraform’s providers act as abstractions of APIs, giving Terraform an interface for working with various resources on host platforms.

      Linode has its own Terraform provider, which you can learn more about from its Terraform
      provider registry page.

      To use the provider, you just need a couple of short blocks in a Terraform script.

      Create a new Terraform file named packer-linode.tf, which acts as the base for this tutorial’s Terraform project:

      Give it the contents shown here:

      File: packer-linode.tf
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      
      terraform {
        required_providers {
          linode = {
            source = "linode/linode"
            version = "1.29.3"
          }
        }
      }
      provider "linode" {
        token = var.token
      }

      The terraform block starts the project by indicating its required providers (e.g. Linode). The provider block then starts the Linode provider. The token argument allows the provider to authenticate its connection to the Linode API.

      When done, press CTRL+X to exit nano, Y to save, and Enter to confirm.

      Assigning Terraform Variables

      Above, you can see that the token value for the Linode provider uses the var.token variable. Although not required, variables make Terraform scripts much more adaptable and manageable.

      This tutorial handles variables using two files.

      1. First, create a variables.tf file:

        Now fill it with the contents shown below. This file defines all the variables for the Terraform project. Some of these variables have default values, which Terraform automatically uses if not otherwise assigned. Other variables need to be assigned, which you can see in the next file.

        File: variables.tf
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        
        variable "token" {
          description = "The Linode API Personal Access Token."
        }
        variable "password" {
          description = "The root password for the Linode instances."
        }
        variable "ssh_key" {
          description = "The location of an SSH key file for use on the Linode instances."
          default = "~/.ssh/id_rsa.pub"
        }
        variable "node_count" {
          description = "The number of instances to create."
          default = 1
        }
        variable "region" {
          description = "The name of the region in which to deploy instances."
          default = "us-east"
        }
        variable "image_id" {
          description = "The ID for the Linode image to be used in provisioning the instances"
          default = "linode/ubuntu20.04"
        }

        When done, press CTRL+X to exit nano, Y to save, and Enter to confirm.

      2. Now create a terraform.tfvars file:

        This file, with the .tfvars ending, is a place for assigning variable values. Give the file the contents below, replacing the values in arrow brackets (<...>) with your actual values:

        File: terraform.tfvars
        1
        2
        3
        4
        
        token = "<LinodeApiToken>"
        password = "<RootPassword>"
        node_count = 2
        image_id = "private/<LinodeImageId>"

        The <LinodeApiToken> needs to be an API token associated with your Linode account. You can follow our
        Get an API Access Token guide to generate a personal access token. Be sure to give the token “Read/Write” permissions.

        Above, you can see a value of private/<LinodeImageId> for the image_id. This value should match the image ID for the Linode image you created with Packer. All custom Linode images are prefaced with private/ and conclude with the image’s ID. In these examples, private/17691867 is assumed to be the ID for the Linode image built with Packer.

        There are two main ways to get your image ID:

        • The Linode image ID appears at the end of the output when you use Packer to create the image. For instance, in the guide on creating a Linode image with Packer linked above, you can find the output:

          ==> Builds finished. The artifacts of successful builds are:
          --> linode.example-linode-image: Linode image: packer-linode-image-1 (private/17691867)
        • The Linode API has an endpoint for listing available images. The list includes your custom images if you call it with your API token.

          You can use a cURL command to list all images available to you, public and private. Replace $LINODE_API_TOKEN with your Linode API token:

          curl -H "Authorization: Bearer $LINODE_API_TOKEN" \https://api.linode.com/v4/images

          The output can be overwhelming in the command line, so you may want to use another tool to prettify the JSON response. This has been done with the result shown here:

          {
              "pages": 1,
              "data": [{
                  "id": "private/17691867",
                  "label": "packer-linode-image-1",
                  "description": "Example Packer Linode Image",
                  // [...]

        When done, press CTRL+X to exit nano, Y to save, and Enter to confirm.

      Defining the Linode Resource

      The next step for the Terraform script is to define the actual resource to be provisioned. In this case, the script needs to provision Linode instances, which can be done using the linode_instance resource.

      Open the packer-linode.tf file created earlier and add the details shown here to the end:

      File: packer-linode.tf
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      
      resource "linode_instance" "packer_linode_instance" {
        count = var.node_count
        image = var.image_id
        label = "packer-image-linode-${count.index + 1}"
        group = "packer-image-instances"
        region = var.region
        type = "g6-standard-1"
        authorized_keys = [ chomp(file(var.ssh_key)) ]
        root_pass = var.password
        connection {
          type = "ssh"
          user = "root"
          password = var.password
          host = self.ip_address
        }
        provisioner "remote-exec" {
          inline = [
            # Update the system.
            "apt-get update -qq",
            # Disable password authentication; users can only connect with an SSH key.
            "sed -i '/PasswordAuthentication/d' /etc/ssh/sshd_config",
            "echo \"PasswordAuthentication no\" >> /etc/ssh/sshd_config",
            # Check to make sure NGINX is running.
            "systemctl status nginx --no-pager"
          ]
        }
      }

      And with that, the Terraform project is ready to provision two Linode instances based on your Packer-built image. Most of the configuration details for the resource block are managed by variables. So you shouldn’t need to fiddle with much of the resource block to adjustment things like the number of instances to provision.

      The remote-exec provisioner, and specifically the inline list within it, is where much of the customization comes in. This block defines shell commands to be executed on the newly provisioned instance. The commands here are relatively simple, but this provisioner can give you fine-grained control of operations on the instance.

      How to Provision a Packer Image with Terraform

      From here, a handful of Terraform commands are all you need to provision and manage Linode instances from the Packer-built image.

      First, Terraform needs to run some initialization around the script. This installs any prerequisites, specifically the linode provider in this example, and sets up Terraform’s lock file.

      Running Terraform’s plan command is also good practice. Here, Terraform checks your script for immediate errors and provides an outline of the projected resources to deploy. You can think of it as a light dry run.

      Review the plan, and when ready, provision your instances with the apply command. This may take several minutes to process, depending on your systems and the number of instances being deployed.

      linode_instance.packer_linode_instance[0] (remote-exec): Connected!
      linode_instance.packer_linode_instance[0] (remote-exec): ● nginx.service - A high performance web server and a reverse proxy server
      linode_instance.packer_linode_instance[0] (remote-exec):      Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
      linode_instance.packer_linode_instance[0] (remote-exec):      Active: active (running) since Thu 2022-10-27 15:56:42 UTC; 9s ago
      [...]
      
      Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

      In the future, whenever you want to remove the instances created with Terraform, you can use the destroy command from within your Terraform script directory.

      As with the apply command, you get a preview of the instances and are asked to confirm before the instances are destroyed.

      Conclusion

      This tutorial outlined how to use Terraform to deploy Linode instances built with a Packer image. This arrangement provides an efficient setup for provisioning and managing Linode instances. Terraform streamlines the process of provisioning infrastructure, and it is made even more efficient using pre-built images from Packer.

      The example covered in this tutorial is fairly simple. But the setup can be readily adapted and expanded on to deploy more robust and complex infrastructures.

      More Information

      You may wish to consult the following resources for additional information
      on this topic. While these are provided in the hope that they will be
      useful, please note that we cannot vouch for the accuracy or timeliness of
      externally hosted materials.



      Source link

      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:[email protected];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