Lesson 13

Taking Control of Backgrounds and Borders

What You’ll Learn in This Lesson:

  • Image How to layer backgrounds

  • Image How to use gradients as backgrounds

  • Image How to use CSS properties to create “zebra-stripe” tables automatically

  • Image How to create rounded corners on elements

  • Image How to use images as borders

  • Image How outlines are different from borders

In earlier lessons you learned how to add basic borders and backgrounds to your elements, but there is much more you can do to dress up modern web pages. In many ways, CSS backgrounds define modern designs. In this lesson you will learn how to layer background images on your elements and use gradients that are created by the CSS itself as backgrounds.

And borders are just as critical. Every element has a border, even if it isn’t visible. In this lesson you will learn how to adjust the borders of your elements to make your designs more interesting. You’ll learn how to create rounded corners as well as how to use images as borders. Plus, you’ll learn a little more about the CSS outline property and how it differs from borders.

Reviewing Background and Border Basics

In order to go into more depth with borders and backgrounds, you need to be sure you know the basics.

background is a shorthand property that allows you to define a number of background properties at the same time. With this property, you can set the following properties:

  • Image background-image—The image used as a background

  • Image background-position—Where the image should be placed on the element, written as a length, a percentage, or a keyword (top, bottom, center, right, and left)

  • Image background-size—The size of the image in the element, either as the width, the width and height, or a keyword (cover or contain)

  • Image background-repeat—Whether and how the image should tile in the element, using one of the values repeat, repeat-x, repeat-y, no-repeat, space, or round

  • Image background-origin—Where the background image should start tiling; possible values are border-box, padding-box, and content-box

  • Image background-clip—How the background should display beyond the element’s content or padding; possible values are border-box, padding-box, or content-box

  • Image background-attachment—How the background should move relative to the viewport; possible values are scroll, fixed, or local

  • Image background-color—The color of the background, using a color keyword or color code

You don’t need to include the properties in the order shown here, but best practices recommend using this order to keep your CSS clear. Some properties, like background-position and background-size, can be left out. Many designers use the background property with just one or two elements, as in these examples:

background: #dfdfdf;
background: url('paper.png') #dfdfdf;

You can apply the background property to any HTML element.

The border property is a shorthand property for setting border-width, border-style, and border-color, like so:

border: border-width border-style border-color;

For the border-width and border-color properties, you can use 10 different border style keywords:

  • Image solid—Draws a solid, continuous line (This is the default.)

  • Image none—Draws no border line

  • Image hidden—Draws a border line but does not display it

  • Image dashed—Draws a line of dashes

  • Image dotted—Draws a line of dots

  • Image double—Draws two lines around the element, taking up the full border width

  • Image groove—Adds a bevel to make the element appear pressed into the page

  • Image ridge—Adds a bevel to make the element appear raised above the page

  • Image inset—Adds a slight bevel to make the element appear slightly depressed

  • Image outset—Adds a slight bevel to make the element appear slightly raised

Using Multiple Borders and Backgrounds

When you’re working with borders and backgrounds, it’s easy to forget that you aren’t stuck with just one. You can style all four borders of an element in different ways, and you can even layer multiple backgrounds, one on top of the other, to create different effects.

Note

Putting more than one border around one element is not currently supported in CSS. However, you can fake it by using pseudo-elements, using the outline property, using the box-shadow property, or changing the background-clip property. You can learn more about how to do this online by searching for multiple borders with CSS in your favorite search engine.

While it’s most common to use just the border property to style all four borders of an element exactly the same, this isn’t your only option. There are four other shorthand properties that work in the same way but each applies to only one side of the element: border-top, border-right, border-bottom, and border-left. For example, if you wanted to style all four borders differently, you would write CSS for all four sides, like so:

border-top: 2px solid red;
border-right: 2px dashed aqua;
border-bottom: 5px dashed red;
border-left: 5px solid aqua;

But it’s not common to see an element that needs vastly different borders on all four sides. Instead, you might see an element that needs three borders the same, with the fourth different. You can write your CSS with the four border properties separated out, or you can use the cascade to your advantage. To do this, define all the borders the same and then follow that with the one different one:

border: 2px solid aqua;
border-bottom: 5px dashed red;

Using multiple backgrounds on the same element is a little different. With CSS3 you can now stack border images on your elements to create a layered effect. This is especially useful if your images have transparent or clipped areas that allow images or color below to show through. You specify multiple backgrounds in a comma-separated list, where each item is a background layer. The order of the items correlates with the order of the layers: The first item is the top layer and on down through the backgrounds.

Note

One of the issues designers most commonly face when using multiple backgrounds is determining the order to place them in the CSS. We can’t count how many times we have carefully created designs only to have one of the backgrounds not show up or appear cut off because we forgot where it belonged in the layer list. Just remember that the layer that is on top comes first.

To create an element with multiple backgrounds, we need multiple images. Figure 13.1 shows an image of a howling wolf and a picture of the moon.

A photograph of the moon. An image of a howling wolf.
Figure 13.1 Two separate images to be combined into a background. (Credit: claudiodivizia/123RF)

Both of these images have transparent areas and solid color areas, so they will work well as layered backgrounds. We also need to add an element to place the background on. The background property can be placed on any block-level HTML element, so we can add a <div> with the class box to the HTML:

<div class="box"></div>

Because the <div> element currently has no content, we need to set the height and width so the background will show up:

.box {
  width: 500px;
  height: 400px;
}

Then we can add the first background image:

background: url(images/wolf.svg)

Remember that this image will be on top, and any other images will be layered below it.

We can position this background image in the middle of the <div> and at the bottom so it looks like the wolf is howling at the moon:

background: url(images/wolf.svg) center bottom

Then, to make sure it doesn’t look bad, we can set the image to fill up the element with the cover and no-repeat keywords:

background: url(images/wolf.svg) center bottom / cover no-repeat

To add the second background image, we add a comma and then the second image URL:

background: url(images/wolf.svg) center bottom / cover no-repeat,
            url(images/moon.png)

We need to put the moon at the top right and make it 45% of the element, and we also need to make sure it displays only once (and be sure to include the closing semicolon):

background: url(images/wolf.svg) center bottom / cover no-repeat,
            url(images/moon.png) right top / 45% no-repeat;

After taking all these steps, the code should look like the code in Listing 13.1, which creates the image shown in Figure 13.2.

Listing 13.1 Adding Multiple Backgrounds

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Layering Backgrounds on an Element</title>
    <style>
      .box {
        margin: 0 auto;
        width: 500px;
        height: 400px;
        background: url(images/wolf.svg) center bottom /
                                         cover no-repeat,
                    url(images/moon.png) right top / 45% no-repeat;
      }
    </style>
  </head>
  <body>
  <div class="box"></div>
  </body>
</html>

A screenshot of a browser window shows the "layering background images.html" page of www.werewolfcss.com. An image of a howling wolf is seen at the foreground and the moon backdrops this.
Figure 13.2 Multiple background images on one element. (Credit: claudiodivizia/123RF)

One of the best reasons for using multiple backgrounds on your web pages is so that you can modify the backgrounds programmatically. For example, we could modify the background in Figure 13.2 with a script so that at different times of day, the moon image is in a different location on the element. With only one background image, we’d have to create multiple images for the different times. But by layering multiple background images, we just need to move the moon picture with the CSS.

Using Forgotten Background Properties

There are several background properties in CSS that designers forget about or hardly ever use. But if you use these properties, you’ll have more control over how the backgrounds display and more tools for animation and interactivity in your web pages.

Choosing How to Place the Background

Background images are placed on boxes, and boxes on web pages are affected by the box model. The box model defines the margins, border, padding, and content area of a box, as you learned in Lesson 10, “Understanding the CSS Box Model and Positioning.” But when you place a background on that box, where does it go? The default placement of a background is behind the content and right up to the border, covering the padding.

The background-clip property lets you change what parts of the box the background covers. These are your choices:

  • Image border-box—This extends the background all the way under the border. If your border is transparent, the background will show through it.

  • Image padding-box—This clips the background within the padding area but leaves the border with no background.

  • Image content-box—This clips the background to the content area only. The padding and border will have no background.

As with all other CSS properties, you can also use the values initial, inherit, and unset on the background-clip property. These values set the background to the default or initial state, the same as the parent element, and remove settings, respectively.

There is another property you can use to adjust how the image displays in the background: the background-origin property. This property might seem like it does the same thing as background-clip, but it is slightly different. It determines the positioning area of the background. The background-clip property specifies whether the background will extend under the border or padding of the element. The background-origin property uses the same three values: border-box, padding-box, and content-box.

Another way to think about the difference between these two properties is that background-origin defines where the background image starts, and background-clip defines where the background image ends.

If you have multiple backgrounds, you can set the background-clip and background-origin for all of them by separating the values with commas. Just as with multiple backgrounds, the first value is for the top layer and down through the list.

Changing the Background Size

When the background-size property made it to browsers, we were in heaven. Finally, there was a way to adjust the size of a background in an element without having to get out a graphics program. But while you don’t need to edit the graphics, background sizes are complex. There are four ways to define the background-size:

  • Image Using keywords

  • Image Using one value

  • Image Using two values

  • Image Using multiple values

Using background-size Keywords

There are three keywords you can use with background-size: auto, cover, and contain. The auto keyword sets the background to be the size it would normally be. cover sets the background image to cover the entire container. The image might be stretched or cropped, but the entire box will have a background. contain resizes the image to fit the entire thing within the box. This means that small images will be stretched to fit, and large images will be shrunk. But if there is extra space (and the background-repeat property allows it), the background will be tiled.

Using background-size Values

You can specify the exact size of a background image by putting in one or two length values. When you use one length, that number is assumed to be the width of the background, and the height is set to auto. When you use two numbers, the first is the width, and the second is the height. You can use any CSS length values, including pixels, percentages, rems/ems, lengths (centimeters, inches, and so on), and viewport relative units, such as vw and vh.

If you have multiple backgrounds layered on an element, you can set their sizes by separating the values with commas:

background-size: 400px 400px, cover;

Positioning Your Background Image

Once you have your background image sized so that it fits the element, you will probably want to have more control over the placement than just the upper-left corner. The background-position property lets you define where the background will be drawn relative to the upper-left corner of the element. You can use the keywords top, bottom, right, left, and center. Or you can use two percentage or length values. One value moves the background right, and two values move it to the right and down.

But what if you want to position your background based on the right or bottom edges? There are two ways to do this: Use background-position with edge offsets or use calc().

To use edge offsets, you first indicate which edge you want to offset from: top, bottom, right, or left. You follow that with a length value. Here is an example:

background-position: top 2rem right 1rem;

This four-value syntax is well supported in all modern browsers. But if you don’t know the exact length of an element—for example, in a responsive design—then using the calc() as a value would make more sense. Describing how calc() works is beyond the scope of this book, but you can search for more information in any search engine.

Changing the Scrolling of Backgrounds

On most web pages, the backgrounds are set to scroll with the browser window. When a customer scrolls down, the background moves up, along with the rest of the content. But with the background-attachment property, you can change how this works. And with the popularity of parallax designs, this is a useful property to know.

These are the values for the background-attachment property:

  • Image scroll

  • Image fixed

  • Image local

Most designers are familiar with the first two: scroll and fixed. A background set to scroll will scroll with the main view (usually the browser window) but will remain fixed inside the local view (usually a container element). A background that is fixed will stay where it is no matter what. The third value, local, was created to allow you to scroll the background with both the main view and the local view.

The easiest way to understand this is to follow along as we build a page with different background attachments. First we create three <div> elements that will have the different attachments:

<div class="inner"><h1>scroll</h1></div>
<div class="inner"><h1>fixed</h1></div>
<div class="inner"><h1>local</h1></div>

Then we surround each of those <div> elements with another <div> and set the classes to scroll, fixed, and local:

<div class="scroll">
  <div class="inner"><h1>scroll</h1></div>
</div>
<div class="fixed">
  <div class="inner"><h1>fixed</h1></div>
</div>
<div class="local">
  <div class="inner"><h1>local</h1></div>
</div>

We then add a paragraph at the bottom of the document with the class addscrollbar to deal with larger browsers:

<p class="addscrollbar"></p>

We need to style all the <div> elements with a height of 300px, a width of 60%, a maximum width of 500px, a margin of 1rem on top and bottom and centered, and hidden horizontal overflow and a scrollbar for the vertical overflow. We can add styles to the inner <div> elements: 100% width, 600px height, and hidden vertical overflow. We can also add a 50rem margin to the .addscrollbar element:

div {
  height: 300px;
  width: 60%;
  max-width: 500px;
  margin: 1rem auto;
  overflow-x: hidden;
  overflow-y: scroll;
}
.inner {
  width: 100%;
  height: 600px;
  overflow-y: hidden;
}
.addscrollbar { margin-bottom: 50rem; }

In order to affect the attachment, you need a background image on the .scroll, .fixed, and .local elements. We can use LoremPixel (http://lorempixel.com) or another random image generator for the images, as shown here:

.scroll, .fixed, .local {
  background-image: url('http://lorempixel.com/600/400/nature/');
}

Then we set background-attachment on the .scroll, .fixed, and .local elements to scroll, fixed, and local respectively:

.scroll { background-attachment: scroll; }
.fixed { background-attachment: fixed; }
.local { background-attachment: local; }

If you load this page in a browser, as you scroll, the backgrounds may or may not scroll with you. Notice how the different values affect whether the background scrolls with the main browser scrollbar or the element scrollbar or both. Listing 13.2 shows the complete HTML and CSS for this example.

Listing 13.2 The Difference Between background-attachment Values

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Learning the Difference Between background-attachment
           Values</title>
    <style>
  div {
    height: 300px;
    width: 60%;
    max-width: 500px;
    margin: 1rem auto;
    overflow-x: hidden;
    overflow-y: scroll;
  }
  .scroll, .fixed, .local {
    background-image: url('http://lorempixel.com/600/400/nature/');
  }
  .scroll {
    background-attachment: scroll;
  }
  .fixed {
    background-attachment: fixed;
  }
  .local {
    background-attachment: local;
  }
  .inner { width: 100%; height: 600px; overflow-y: hidden; }
  .addscrollbar { margin-bottom: 50rem; }
    </style>
  </head>
  <body>
    <div class="scroll">
      <div class="inner"><h1>scroll</h1></div>
    </div>
    <div class="fixed">
      <div class="inner"><h1>fixed</h1></div>
    </div>
    <div class="local">
      <div class="inner"><h1>local</h1></div>
    </div>
    <p class="addscrollbar"></p>
  </body>
</html>

Alternating Background Colors

When you build tables, especially large ones with a lot of data, coloring the background of the rows can make them much easier to read. To do this, you don’t use a background-* CSS property but rather the :nth-child() pseudo-class.

In the past, designers would sometimes create a class in their CSS with a background color and then add that class to every other row in a table. But with the :nth-child() pseudo-class, you can select one or more elements based on the order in which they appear in the source HTML. This means that if the table has 10 body rows today and 13 tomorrow, you don’t have to go in and edit the class on every row. The CSS will update automatically.

The :nth-child() selector takes an attribute in the parentheses. This attribute can be one of the following:

  • Image A single integer—Selects just that one element, such as the fourth row in a table, like so: tr:nth-child(4)

  • Image even—Selects only the even-numbered elements

  • Image odd—Selects only the odd-numbered elements

  • Image A formula—Selects the elements that match the formula an+b, where a is an integer, n is the literal letter n, + is an operator that may be either + or -, and b is another integer

To create zebra-stripe tables, you can just use the even or odd keywords, like so:

tbody tr:nth-child(odd) { background-color: #dfdfdf; }

This tells the browser to examine every row inside the <tbody> element and add a gray background to the first row, third row, fifth row, and so on.

The real power in using the :nth-child selector is with the formula. It allows you to make complicated selections, such as these:

  • Image Every other element, starting with the fifth one:nth-child(2n+5)

  • Image Every sixth element, starting with the second one:nth-child(6n+2)

You can also use other pseudo-class selectors to select specific elements in your DOM tree, including the following:

  • Image :nth-of-type()—Selects based on the element type, such as <p>, <li>, <tr>, and so on.

  • Image :nth-last-child()—Selects just like :nth-child() but starting at the bottom of the parent element and selecting up the DOM tree

  • Image :nth-last-of-type()—Selects based on type but works up from the bottom of the DOM tree

For a useful tester you can use to try out different formulas to see how they work, visit http://lea.verou.me/demos/nth.html.

Using Gradients as Backgrounds

Gradients have been popular on the web for as long as we’ve had images on web pages. Adding them used to be very difficult. You had to be willing to use gigantic images with lots of colors and very little compression. If you didn’t you’d end up with blocky color swaths with bands striping down your page. Sites with smooth gradients were guaranteed to load more slowly. Most designers just left them out completely. Now the combination of modern CSS and modern browsers allows web designers to create beautiful gradients without any images at all.

Caution

This may seem counterintuitive, but when you add gradients to your backgrounds, you add them as background images with the background-image or the background shorthand property. You can use these properties as a fallback for older browsers that don’t support gradients. Simply define both the background-image with the gradient and the background-color with a default color. Browsers that support gradients then place the gradient above the background color, and older browsers just display the color and ignore the gradient.

There are two types of gradients: linear and radial.

Creating Linear Gradients

Linear gradients are gradients that change color along a straight line. They can move horizontally from left to right, vertically from top to bottom, or across any diagonal angle you choose. The default is vertical, or top to bottom. You set a linear gradient by using the linear-gradient() expression, with a comma-separated list of colors inside the parentheses. For example, you can create a gradient from pink (#ff00d5) to green (rgba(39, 164, 0, 0.5)) to blue like so:

background-image:
  linear-gradient( #ff00d5, rgba(39, 164, 0, 0.5), blue );

The colors can be any color values that are valid in CSS, including named colors, RGBa, hexadecimal, HSL (hue, saturation, and lightness), and so on. You need at least two colors to create a gradient.

After you define your colors, you can indicate where you want them to start. This is called a color stop. If you don’t include any color stops, the gradient will be applied evenly across the space. Add the color stops after each color value but before the comma separating the next color, like so:

background-image:
  linear-gradient(
    red,
    green 35%
  );

You add the location of the color stop as a length notation after the color.

If you want to change the direction of the gradient, you add a parameter that is the word to and the direction before the colors. The following are some examples:

  • Image to right—The gradient moves from left to right.

  • Image to left—The gradient moves from right to left.

  • Image to top—The gradient moves from bottom to top.

  • Image to top left—The gradient moves from the bottom-right corner diagonally up to the top-left corner.

  • Image 45deg—The gradient moves along a 45° angle with 0deg being completely vertical and 90deg being horizontal and equivalent to to right.

Linear gradients can make very nice-looking backgrounds, and they don’t add a lot of download time to a page.

Building Radial Gradients

Radial gradients are similar to linear gradients. They take two or more colors and fade from one to the next. But whereas linear gradients fade down a line, radial gradients start at a single point and emanate outward. A default radial gradient starts in exactly the center of the element and moves outward to the edge. It is written just like a linear gradient but with the expression radial-gradient(). A basic radial gradient fading from light blue in the center (#9ad6e9) to yellow is written thus:

background-image: radial-gradient(
  #9ad6e9,
  yellow
);

A gradient makes an ellipse by default unless you place it on a square element. Figure 13.3 shows the same gradient on <div> elements of two different shapes. Listing 13.3 shows the HTML and CSS for this figure.

In the screenshot, a radial gradient is shown over two elements: a square, and a vertically oriented rectangle. The gradient takes the shape of a circle in the first case (square element), and an ellipse in the second element. The color is more dense at the center and fades outward.
Figure 13.3 A radial gradient on two different elements.

Listing 13.3 A Radial Gradient on Two Different Elements

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>A Radial Gradient on Two Different Elements</title>
    <style>
      .container {
        width: 45rem;
        margin: 0 auto;
      }
      .grad { background-image: radial-gradient(
        orange,
        white);
        border: solid 1px black;
        margin: 1rem;
        float: left;
      }
      .one {
        width: 30rem;
        height: 30rem;
      }
      .two {
        width: 10rem;
        height: 30rem;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="grad one"></div>
      <div class="grad two"></div>
    </div>
  </body>
</html>

The gradient looks different on the square element because it has a circular shape, while the element itself is square. You can force the gradient to be circular by adding the shape at the beginning, like so:

background-image: radial-gradient(
circle,
#9ad6e9,
yellow
);

Otherwise, the default value is ellipse.

You can also adjust the size of the ellipse by defining a size, using the following values:

  • Image closest-side—The gradient shape is sized to meet the side closest to the center.

  • Image closest-corner—The gradient shape is sized to meet the corner closest to the center.

  • Image farthest-side—The gradient shape is sized to meet the side of the element farthest from the center.

  • Image farthest-corner—The gradient shape is sized to meet the corner of the element that is farthest from the center.

One way to think of the keywords is to add them to this sentence: “I want my radial gradient to start at the center point and fade to the ____, filling in the rest of the element accordingly.” Add them to the first parameter, as in this example:

circle closest-side,

Caution

Early drafts of the CSS specification included two other keywords for defining radial gradients: contain and cover. These were intended to act as synonyms for closest-side and farthest-corner, respectively. They were subsequently removed from the specification, and most modern browsers have removed support for them (if they ever did support them). Use the closest-side and farthest-corner keywords instead.

If you want the placement of the center of your gradient to be more precise, you can use the at keyword along with positioning keywords or values. These are the keywords you can use:

  • Image left

  • Image center

  • Image right

  • Image top

  • Image bottom

The following example shows how to use the at keyword and parameters:

circle at bottom right,

You can also use exact positions in lengths or percentages for the distance from the top and the left side of the element. For example, Figure 13.4 displays two gradients placed next to one another. One has an origin at the bottom left and the other at the bottom right. Listing 13.4 shows the CSS used to create this effect.

Two radial gradients of similar elements are merged and placed next to each other.
Figure 13.4 Radial gradients create an interesting effect.

Listing 13.4 Two Radial Gradients Create an Interesting Effect

.one {
  background-image: radial-gradient(
    at bottom left,
    orange,
    white
  );
}
.two {
  background-image: radial-gradient(
    at bottom right,
    orange,
    white
  );
}

And just as with linear gradients, with radial gradients you can define color stops to identify exactly where you want the colors to change. For example, this is a three-color circular gradient centered in the lower-right portion of the element:

.gradient {
  background-image: radial-gradient(
    circle at 70% 64%,
    orange,
    #25b25d 18%,
    gray 77%
  );
}

Rounding the Corners of HTML Elements

As you’ve learned in earlier lessons, HTML elements are all rectangular blocks, and this can make web pages look very boxy and rigid. But with the border-radius properties, you can make the corners as round or square as you like. Simply define the amount of curve you want for the corners, like so:

border-radius: 1rem;

Note

An easy way to remember the style property border-radius is to imagine there is a circle in each corner of your element. The radius of that circle determines the size of the curve.

As long as there is a color change of some sort, the rounded corner will be visible and will curve all four corners of the element. Listing 13.5 shows three <div> elements with rounded corners that are identical except that the first one has a background color, the second has a border, and the third has a background image. Figure 13.5 shows how this would look.

Listing 13.5 Three <div> Elements with Rounded Corners

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Three DIVs with Rounded Corners</title>
    <style>
      div {
        border-radius: 1rem;
        width: 10rem;
        height: 15rem;
        float: left;
        margin: 1rem;
        box-sizing: border-box;
      }
      .one { background-color: aqua; }
      .two { border: solid 0.25rem aqua; }
      .three { background: url(images/mckinley.jpg)
        center top / cover no-repeat; }
    </style>
  </head>
  <body>
    <div class="one"></div>
    <div class="two"></div>
    <div class="three"></div>
  </body>
</html>

A screenshot shows three <div> elements. All three elements have rounded corners. The first element is filled with a background color, the second element is empty but has a colored border, and the third element has a background image of a dog.
Figure 13.5 Three <div> elements with rounded corners.

With the border-radius property you can set all four corners at once, or you can set them to different values. This property can take between one and four values.

You can use one value to set all four corners the same. If you use two values, you set first the top-left and bottom-right corners to the first value and then set the top-right and bottom-left corners to the second value. If you use three values, you set the top-right and bottom-left corners to the second value, with the first value setting the top-left corner and the third value setting the bottom-right corner. You can use four values to set all four corners, in this order: top-left corner, top-right corner, bottom-right corner, and bottom-left corner. Consider these examples:

  • Image border-radius: 1rem;—All four corners are 1rem radius.

  • Image border-radius: 1rem 0.5rem;—The top-left and bottom-right corners are 1rem. The top-right and bottom-left corners are 0.5rem.

  • Image border-radius: 1rem 0.5rem 0.25rem;—The top-left corner is 1rem. The top-right and bottom-left corners are 0.5rem. The bottom-right corner is 0.25rem.

  • Image border-radius: 1rem 0.75rem 0.5rem 0.25rem;—The top-left corner is 1rem. The top-right corner is 0.75rem. The bottom-right corner is 0.5rem, and the bottom-left corner is 0.25rem.

One fun thing you can do is turn any element into a circle or an ellipse with the border-radius: 50%; style property. If the element has equal height and width, it will display as a circle. If the height and width are different, it will display as an ellipse.

Using Images as Borders

Borders can be more than just plain colors. You can do a lot with borders by curving the edges, as you learned in the last section, and also by changing their width and style, as you learned in Lesson 10. However, you can’t create every effect you might want with borders.

One thing that many designers look for is a way to frame images with another image. Rather than make a solid-color border surrounding an element, you might want a frame like one you would see around a painting. To do this, you need a picture of the frame.

Defining the Border Image: border-image-source

CSS allows you to define any picture as a border by using the border-image property. This is a shorthand property that defines several other properties. One such property is the URL of the image that will become the border, which is defined as border-image-source. The default value for border-image-source is none, but if you specify an image URL, then that image will be used as the border for the element, like so:

.myBorder {
  border-image-source: url(border.png);
}

Clipping the Border Image: border-image-slice

The border-image property also defines the border-image-slice property. In order to create decent borders, you need to tell the browser where each portion of the border will be by slicing the border into nine sections. These sections are illustrated in Figure 13.6.

The border image slice property.
Figure 13.6 Slicing an image to use as a border.

The border-image-slice property takes up to four positive values, either numbers or percentages, and an optional fill keyword. The numbers, which are unitless, measure the coordinates of the slices by pixels on raster images like JPEG or PNG and by coordinates on SVG images. If you use percentages, this is relative to the size of the image itself. The four values measure inward from the top, right, bottom, and left edges of the image:

border-image-slice: top right bottom left;

This divides the image into nine regions: four corners, four edges, and the center. In most cases, the center is discarded, and only the corners and edges are used for the border.

Note

The border-image-slice property can have slices that are 0 pixels away from the side. This allows you to create image borders that are applied only to a couple sides of an element rather than all four. For example, if you want to add a border that looks like a ruler, you might place that on only the top or right side of the element. When you slice the border image, the left and bottom sides are zero, and they are not applied to the border.

As mentioned previously, the border-image-slice property can also take the keyword fill. This tells the browser to keep the middle part of the image and display that section as a background image on the element. You can therefore add a background image with a fancy border to your element and have that border be repeated no matter the size of the element. To use the fill keyword, add it after the offsets, like this:

border-image-slice: 10 5 8 7 fill;

Figure 13.7 shows how a simple image can be sliced and used to fill an element or just create the border. For this image, we used a picture from Pixabay of a series of flowers and sliced it so that only the outer rows and columns are part of the border.

Slicing an image to to create a border and to fill a border.
Figure 13.7 Using a sliced image for a border and a filled border.

Defining the Border Image Width

One property that is confusing to people when they first start using border images is border-image-width. This is different from the slice offsets because it defines the width of the border image regardless of the offset. The initial value is 1, so if you need the border to be blank on one or more sides, you should specify border-image-width for those sides as 0. Otherwise, if there is a border or border-width set on the element, that border will display.

This property uses the top, right, bottom, left order for the values. You can use percentages relative to the size of the border image area or unitless non-negative numbers that are multiplied by border-width.

Extending the Border Image Beyond the Border Edges

If you want your border image to extend past the border box area, you can use the border-image-outset property. Border images do not affect the width of the border, and wider borders are inset, covering the padding and even the content area of the element. When you add an outset, this tells the browser to display the border image outset over the element margin.

Making the Border Fit

One thing you’ll notice when you start using border images is that they don’t fit around every element. Browsers automatically repeat the image as they would with tiled background images to make the border images fit in the space available. There are four ways a browser can do this with the border-image-repeat property:

  • Image stretch—The border image is simply stretched to fit the space. If the space is too wide, that slice will be increased, and if it’s too narrow, the slice will be compressed. This is the default value.

  • Image repeat—This keyword tiles the image to fill the area. If necessary, the tiles will be cut to fit the space.

  • Image round—This keyword tiles the image to fill the area, but the image is resized and scaled to fit so that tiles are not divided or cut.

  • Image space—This keyword tiles the image to fill the area, but if whole tiles cannot be used, space is inserted around the tiles to create an even fit. This keyword may not be supported by Chrome, Android, or Opera browsers. However, when we tested it in Chrome, it appeared to work.

Figure 13.8 shows the border-image-repeat property on four elements. For this figure, we cropped the flower border image so that it was only nine flowers (a 3 × 3 grid) and resized it to be 100 × 100 pixels. If you use a border image that is larger than the elements you’re bordering, you can get unexpected results, especially with the round and space keywords. The former can end up looking identical to stretch, while the latter is simply blank because there isn’t enough space in the slice to include the whole thing.

Previews of different repeating styles on a border image.
Figure 13.8 Different repeating styles on border images.

Caution

Most novice web designers think that the border-image and related properties should allow you to create a repeating border around the element without slicing the image at all. But that is not how these properties work. In order to create a repeating image, you need to create a 9 × 9 grid of the image (you can leave out the central image) and then slice the image with the border-image-slice property. Figure 13.9 shows a 9 × 9 grid of flowers that we used to create a repeating flower border in Figure 13.7.

A border image comprising of a 3 cross 3 grid of flowers.
Figure 13.9 A 9 × 9 grid of flowers can be used to create a repeating flower border.

Understanding CSS Outlines

An outline is a line around visible objects on the web page that is designed to make the object stand out. According to the W3C, outlines are different from borders in three ways:

  • Image Outlines do not take up space.

  • Image Outlines may be non-rectangular.

  • Image Browsers and other user agents often render outlines on elements when they are in the :focus state.

Because outlines don’t take up space, they can cover content, are usually drawn outside the element’s border, and don’t add to the dimensions of the element. They are not part of the box model.

Because outlines may be non-rectangular, they may display differently in different browsers. This is especially true when the outline is applied to an inline element such as <span>. Some browsers follow the actual contours of the letters with the outline, while others treat the inline element as a rectangular box. Both display methods are valid, but you should be aware of these differences when using CSS outline properties.

Another thing that some browsers do is display the outline of links and other elements when they have been focused on but haven’t been clicked. This allows users to see what link may be about to be clicked; this is especially important for accessibility.

Caution

You should never use outline: none; or outline: 0; on links or buttons or other elements that receive keyboard focus. Such an outline tells keyboard users which link currently has focus, and without it, they can’t navigate your site. If you must remove the outline, then be sure to redefine any :focus states with some other way to recognize the state change, such as a color change, font change, or other indicator.

There are five outline properties: outline-style, outline-color, outline-width, outline-offset, and outline. They work in the same way as the border properties, with outline being a shorthand property where you can define outline-style, outline-color, and outline-width all at once, like so:

outline: 8px ridge yellow;

The outline-offset property defines the amount of space between the outline and the edge or border. The default value is 0, and it can take any length value, including negative numbers if you want the outline to be shown above the content or border. Here is an example:

outline-offset: .4rem;

Summary

In this lesson you learned several advanced techniques for background images and borders. First, you learned how to adjust the four borders on any element and set them all individually to create an element with several different borders. You also learned how to layer multiple backgrounds on one element to create interesting effects. This lesson covered how to position background elements with the background-clip property, how to change the size of the background with background-size, and how to use the background-position and background-attachment properties. You also learned about how to use some other lesser-known CSS properties to create a zebra-striped table. In the section on gradients, you learned about both linear and radial gradients. This lesson also covered how to round the corners of elements with the border-radius property and how to use images as borders with the border-image properties. Finally, you learned about the CSS outline properties and how they differ from border properties.

Q&A

Q. What is the best way to create a responsive background image for a web page?

A. Responsive web pages need to have background images that are large enough to cover big monitors but small enough to download quickly on mobile devices. You have several options for creating a decent background image, including using a small PNG as a repeating background or seamless tile, using flat color or gradients, or using an SVG file that can scale appropriately. You will learn more about responsive web design in Part IV, “Responsive Web Design.”

Q. Are there rules for when you should use an <img> tag versus using a background image?

A. The <img> tag is a part of the HTML and as such is part of the content of the page. It can be printed and animated, but it is considered page content that should be rendered in some fashion even if the user agent is not a visual device such as a screen reader.

Background images are part of the background. They generally are not considered content and will be ignored by visual user agents. They are typically used as decoration or enhancement of existing content. Sprites are usually created using background images.

Workshop

The Workshop contains quiz questions and activities to help you solidify your understanding of the material covered.

Quiz

1. What types of HTML elements (such as block or inline) can have background images?

2. What is the keyword for creating a border that makes the element appear pressed into the page?

3. What are two ways you can give an element a red, dotted, 2px border on the top side and a blue, double 10px border on the right and left sides, leaving the bottom side with no border?

4. How do you separate multiple background images in the background property when layering them on one element?

5. Where does the background display when background-clip is set to content-box?

6. What does the selector li:nth-child(even) select?

7. What corners are rounded with the CSS style border-radius: 10px 5px 15px;?

8. What CSS property defines the URL used as a border image?

9. What does the fill keyword do in the border-image-slice property?

10. What are the three ways CSS outlines are different from borders?

Note

Just a reminder for those of you reading these words in the print or e-book edition of this book: If you go to www.informit.com/register and register this book (using ISBN 9780672338083), you can receive free access to an online Web Edition that not only contains the complete text of this book but also features an interactive version of this quiz.

Answers

1. Backgrounds can be applied to any HTML element.

2. The border-style keyword groove makes the element appear pressed into the page.

3. You can define all four borders separately, like so:

border-top: 2px dotted red;
border-right: 10px double blue;
border-bottom: none;
border-left: 10px double blue;

Or you can define all four borders the same and then change just the two different ones, like so.:

border: 10px double blue;
border-top: 2px dotted red;
border-bottom: none;

4. You use commas to separate the layered background images.

5. The background will display behind the content only. The padding and border will have no background.

6. It selects every even-numbered <li> element in the DOM.

7. The top-left corner is 10px, the top-right and bottom-left corners are 5px, and the bottom right is 15px.

8. The border-image-source property defines the image source for any border image.

9. It tells the browser to keep the middle part of the image as a background image on the element.

10. They don’t take up space, they may be non-rectangular, and browsers often render them when the element is in a :focus state.

Exercises

  • Image Use what you’ve learned in this lesson to add a linear gradient to the background of your web page or an element on the page. Remember that gradients work best on elements that have defined dimensions, so be sure to set them in your CSS.

  • Image Once you have a gradient on an element, layer an image above it in the background. This is one of the most common ways to use layered backgrounds. Rather than set multiple images, you set the top layer as an image and the bottom layer as a gradient.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
44.222.249.19