背景と枠線

このレッスンでは、CSS の背景と境界線を使ってできるクリエイティブなことをいくつか見ていきます。グラデーションや画像による背景や、角丸と境界線といったものを施していくなかで、CSS のスタイリングに関する多くの疑問を解消していきます。

前提条件: 基本的なコンピューターリテラシー、基本的なソフトウェアがインストールされていること、ファイルの扱い、HTML の基本(HTML 入門)および CSS に関するアイデア(CSS の第一歩)に関する基本的な知識を得ている。
目的: ボックスの背景と枠線をスタイルする方法を学ぶ。

CSS による背景の設定

The CSS background property is a shorthand for a number of background longhand properties that we will meet in this lesson. If you discover a complex background property in a stylesheet, it might seem a little hard to understand as so many values can be passed in at once.

.box { 
  background: linear-gradient(105deg, rgba(255,255,255,.2) 39%, rgba(51,56,57,1) 96%) center center / 400px 200px no-repeat, 
  url(big-star.png) center no-repeat, rebeccapurple; 
} 

We'll return to how the shorthand works later in the tutorial, but first let's have a look at the different things you can do with backgrounds in CSS, by looking at the individual background properties.

背景色

The background-color property defines the background color on any element in CSS. The property accepts any valid <color>. A background-color extends underneath the content and padding box of the element.

In the example below we have used various color values to add a background color to the box, a heading, and a <span> element.

Play around with these, using any available <color> value.

背景画像

The background-image property enables the display of an image in the background of an element. In the example below we have two boxes — one has a background image which is larger than the box, the other has a small image of a star.

This example demonstrates two things about background images. 既定では, the large image is not scaled down to fit the box, so we only see a small corner of it, whereas the small image is tiled to fill the box. In this case the actual image is just a single star.

If you specify a background color in addition to a background image then the image displays on top of the color. Try adding a background-color property to the example above to see that in action.

背景画像の繰り返し方法の指定

The background-repeat property is used to control the tiling behavior of images. The available values are:

  • no-repeat — stop the background from repeating altogether.
  • repeat-x — repeat horizontally.
  • repeat-y — repeat vertrically.
  • repeat — the default; repeat in both directions.

Try these values out in the example below. We have set the value to no-repeat so you will only see one star. Try out the different values — repeat-x and repeat-y — to see what their effects are.

背景画像のサイズ指定

In the example above, we have a large image that has ended up being cropped as it is larger than the element it is a background of. In this case we could use the background-size property, which can take length or percentage values, to size the image to fit inside the background.

You can also use keywords:

  • cover — the browser will make the image just large enough so that it completely covers the box area while still retaining its aspect ratio. In this case some of the image is likely to end up outside the box.
  • contain — the browser will make the image the right size to fit inside the box. In this case you may end up with gaps on either side or on the top and bottom of the image, if the aspect ratio of the image is different to that of the box.

In the example below I have used the larger image from the example above, and used length units to size it inside the box. You can see this has distorted the image.

Try the following.

  • Change the length units used to modify the size of the background.
  • Remove the length units and see what happens when you use background-size: cover or background-size: contain.
  • If your image is smaller than the box, you can change the value of background-repeat to repeat the image.

背景画像の位置の指定

The background-position property allows you to choose the position in which the background image appears on the box it is applied to. This uses a coordinate system in which the top-left-hand corner of the box is (0,0), and the box is positioned along the horizontal (x) and vertical (y) axes.

: The default background-position value is (0,0).

The most common background-position values take two individual values — a horizontal value followed by a vertical value.

You can use keywords such as top and right (look up the others on the background-image page):

.box { 
  background-image: url(star.png); 
  background-repeat: no-repeat; 
  background-position: top center; 
} 

And Lengths, and percentages:

.box { 
  background-image: url(star.png); 
  background-repeat: no-repeat; 
  background-position: 20px 10%; 
} 

You can also mix keyword values with lengths or percentages, 例えば、:

.box {
  background-image: url(star.png);
  background-repeat: no-repeat;
  background-position: top 20px;
}

Finally, you can also use a 4-value syntax in order to indicate a distance from certain edges of the box — the length unit in this case is an offset from the value that preceeds it. So in the CSS below we are positioning the background 20px from the top and 10px from the right:

.box { 
  background-image: url(star.png); 
  background-repeat: no-repeat; 
  background-position: top 20px right 10px; 
} 

Use the example below to play around with these values and move the star around inside the box.

: background-position is a shorthand for background-position-x and background-position-y, which allow you to set the different axis position values individually.

グラデーション背景

A gradient — when used for a background — acts just like an image and is also set by using the background-image property.

You can read more about the different types of gradients and things you can do with them on the MDN page for the <gradient> data type. A fun way to play with gradients is to use one of the many CSS Gradient Generators available on the web, such as this one. You can create a gradient then copy and paste out the source code that generates it.

Try some different gradients in the example below. In the two boxes respectively we have a linear gradient which is stretched over the whole box, and a radial gradient with a set size, which therefore repeats.

複数の背景画像

It is also possible to have multiple background images — you specify multiple background-image values in a single property value, separating each one with a comma.

When you do this you may end up with background images overlapping each other. The backgrounds will layer with the last listed background image at the bottom of the stack, and each previous image stacking on top of the one that follows it in the code.

: Gradients can be happily mixed with regular background images.

The other background-* properties can also have values comma-separated in the same way as background-image:

background-image: url(image1.png), url(image2.png), url(image3.png), url(image1.png);
background-repeat: no-repeat, repeat-x, repeat;
background-position: 10px 20px,  top right;

Each value of the different properties will match up to the values in the same position in the other properties. Above, 例えば、image1's background-repeat value will be no-repeat. However, what happens when different properties have different numbers of values? The answer is that the smaller numbers of values will cycle — in the above example there are four background images but only two background-position values. The first two position values will be applied to the first two images, then they will cycle back round again — image3 will be given the first position value, and image4 will be given the second posiition value.

Let's play. In the example below I have included two images. To demonstrate the stacking order, try switching which background image comes first in the list. Or play with the other properties to change the position, size, or repeat values.

背景画像とスクロール

Another option we have available for backgrounds is specifying how they scroll when the content scrolls. This is controlled using the background-attachment property, which can take the following values:

  • scroll: Causes the element's background to scroll when the page is scrolled. If the element content is scrolled, the background does not move. In effect, the background is fixed to the same position on the page, so it scrolls as the page scrolls.
  • fixed: Causes an element's background to be fixed to the viewport, so that it doesn't scroll when the page or element content is scrolled. It will always remain in the same position on the screen.
  • local: This value was added later on (it is only supported in Internet Explorer 9+, whereas the others are supported in IE4+) because the scroll value is rather confusing and doesn't really do what you want in many cases. The local value fixes the background to the element it is set on, so when you scroll the element, the background scrolls with it.

The background-attachment property only has an effect when there is content to scroll, so we've made a demo to demonstrate the differences between the three values — have a look at background-attachment.html (also see the source code here).

背景に関する指定をまとめておこなう

As I mentioned at the beginning of this lesson, you will often see backgrounds specified using the background property. This shorthand lets you set all of the different properties at once.

If using multiple backgrounds, you need to specify all of the properties for the first background, then add your next background after a comma. In the example below we have a gradient with a size and position, then an image background with no-repeat and a position, then a color.

There are a few rules that need to be followed when writing background image shorthand values, 例えば、:

  • A background-color may only be specified after the final comma.
  • The value for background-size may only be included immediately after background-position, separated with the '/' character, like this: center/80%.

Take a look at the MDN page for background to see all of the considerations.

背景に関するアクセシビリティ

When placing text on top of a background image or color, you should take care that you have enough contrast for the text to be legible for your visitors. If specifying an image, and text will be placed on top of that image, you should also specify a background-color that will allow the text to be legible if the image does not load.

Screen readers cannot parse background images, therefore they should be purely decoration; any important content should be part of the HTML page and not contained in a background.

枠線

When learning about the Box Model, we discovered how borders affect the size of our box. In this lesson we will look at how to use borders creatively. Typically when we add borders to an element with CSS we use a shorthand property that sets the color, width, and style of the border in one line of CSS. We can set a border for all four sides of a box with border .

.box { 
  border: 1px solid black; 
} 

Or we can target one edge of the box, 例えば、:

.box { 
  border-top: 1px solid black; 
} 

The individual properties for these shorthands would be:

.box { 
  border-width: 1px; 
  border-style: solid; 
  border-color: black; 
} 

And for the longhands:

.box { 
  border-top-width: 1px; 
  border-top-style: solid; 
  border-top-color: black; 
} 

: These top, right, bottom, and left border properties also have mapped logical properties which relate to the writing mode of the document (e.g. left-to-right or right-to-left text, or top-to-bottom). We'll be exploring these in the next lesson, which covers handling different text directions.

There are a variety of styles that you can use for borders. In the example below we have used a different border style for the four sides of my box. Play with the border style, width, and color to see how borders work.

角丸

Rounding corners on a box is achived by using the border-radius property and associated longhands which relate to each corner of the box. Two lengths or percentages may be used as a value, the first value defining the horizontal radius, and the second the vertical radius. In a lot of cases you will only pass in one value, which will be used for both.

例えば、to make all four corners of a box have a 10px radius:

.box { 
  border-radius: 10px; 
} 

Or to make the top right corner have a horizontal radius of 1em, and a vertical radius of 10%:

.box { 
  border-top-right-radius: 1em 10%; 
} 

We have set all four corners in the example below, and then changed the values for the top right corner to make it different. You can play with the values to change the corners. Take a look at the property page for border-radius to see the available syntax options.

背景と枠線を試す

To test out your new knowledge try to create the following using backgrounds and borders, using the example below as a starting point:

  1. Give the box a 5px black solid border, with rounded corners of 10px.
  2. Add a background image (use the URL balloons.jpg) and size it so that it covers the box.
  3. Give the <h2> a semi-transparent black background color, and make the text white.

: You can take a look at the solution here — but try to figure it out yourself first!

まとめ

We have covered quite a lot here, and you can see that there is quite a lot to adding a background or a border to a box. Do explore the different property pages if you want to find out more about any of the features we have discussed. Each page on MDN has more examples of usage for you to play with and enhance your knowledge.

In the next lesson we will find out how the Writing Mode of your document interacts with your CSS. What happens when text does not flow from left to right?

このモジュール

  1. カスケードと継承
  2. CSS セレクター
  3. ボックスモデル
  4. 背景と枠線
  5. テキスト方向の操作
  6. 要素のはみ出し(オーバーフロー)
  7. CSS の値と単位
  8. CSS によるサイズ設定
  9. 画像・メディア・フォーム要素
  10. 表のスタイリング
  11. CSS のデバッグ
  12. CSS の整理