CSS 배경 이미지 사용

개요

이 강좌는 CSS 배경을 상세하게 다룬다: 배경색, 이미지, 반복, 첨부 파일, 위치. 끝 부분에서, CSS 스프라이트와 같은 고급 기술도 살펴본다.

소개

인정하자! Web Standards Curriculum 의 첫 강좌 이후, 당신의 사이트를 격렬하고 멋지게 만드는 방법을 배우기 위해 흥분되었다. 이 섹션으로 건너 뛰지는 않았는가?

배경 이미지는 사이트를 멋지게 만드는 모든 것이다. 그러나 이것들이 얼마나 많이 이미 배운 기본 개념을 기반으로 하는지 놀랄것이다.

이전의 강좌에서 이미 배웠듯이, CSS에서 가장 중요한 변화는 presentation (보여주는 방식)과 semantics (의미하는 것)을 분리한 기능이다. CSS 배경 이미지는 당신이 원하는 대로 쓰는 가장 중요한 도구 중의 하나이다. 왜냐하면 HTML에 어떤 것도 추가하지 않고, HTML의 특정 부분에 장식 이미지를 적용할 수 있기 때문이다. 이전에는, 작성자(당신과 같은!)는 같은 효과를 내기 위해, 코드에 img 태그를 채워야 했다.

CSS 및 특히 background 속성은 HTML에서 보여 주기 위한 잡동사니들을 없앴다. 현대적인 방법으로 만들어진 사이트는, 훨씬 효율적으로 재설계 및 기타 전환을 할 수 있다. 스타일 시트만 변경하면, 모든 페이지의 코드를 다시 작성하지 않고, 전체 사이트를 수정할 수 있다. 사이트의 크기에 따라, 상당한 시간을 절약할 수 있다.

이 강좌에서, CSS 배경 이미지 작동 방법의 기초를 배울 것이다. CSS를 통한 배경 이미지 적용 방법, 배경이미지 위치 조정, 수직 또는 수평으로 늘어 놓기 및 site performance 를 개선하기 위해 CSS Sprites 를 사용하여 배경이미지를 결합하는 방법 등을 알게 될 것이다.

어떻게 작동하나 (How does it work)?

배경을 위한 CSS는 여러 가지 다른 속성으로 나눠진다. positioncolor 속성을 사용하면, 페이지의 모양과 느낌을 제어하기 시작할 수 있다. 이 강좌에서, CSS 배경 이미지를 상세히 살펴볼 것이다. 예제로 경고 메시지를 단계적으로 만들어 본다.

우선, 사용할 수 있는 속성들을 살펴보자.

배경 속성

속성 정의 설명
background-color HTML 요소의 배경색을 설정한다.

background-color 을 표시하는 방법은 여러 가지가 있다. RGB 값과 키워드가 포함된다. 대부분의 사람들은 16진법 표기법, 파운드/해시 기호 (#)와 여섯 개의 문자 조합을 사용한다. 처음 두 자리는 red 수준, 두 번째와 세 번째는 각각 green과 blue 수준을 나타낸다—#RRGGBB.

많은 색상 선택기 도구는 특정 색상의 16진수 코드를 찾는데 도움을 준다. 예를 들어, 순수 red는 #FF0000 이다.

Photoshop color picker displays the hex value of your color

유효한 값으로는 colour 값, transparent, 또는 inherit 이 있다.

image 배경 이미지의 경로 또는 URL 을 나타낸다.

URL을 사용하여 브라우저에게 이미지가 있는 곳을 알려주어, background-image를 설정한다 예를 들어; url(alert.png). 경로는 키워드 url 이 앞에 오고 괄호로 감싸는 것에 주목하자. 이 구문은 중요하다. 위치를 지시한다는 것을 브라우저가 이해하게 된다.

유효한 값으로는 URL, none, inherit 이 있다.

repeat 배경 이미지를 늘어 놓는 방향을 지시한다.

HTML 요소의 전체 폭과 높이를 채우기 위해, 이미지를 수직, 수평, 또는 양방향으로 늘어 놓을 수 있다. 브라우저에게 배경 이미지 반복을 지시하기 위해 background-repeat 를 사용한다.

유효한 값으로는 repeat, repeat-x, repeat-y, no-repeat 가 있다.

attachment 사용자가 스크롤할 때 배경 이미지의 행동을 설정한다.

이미지는 내용과 함께 스크롤 되거나, 화면에서 제자리에 고정될 수 있다. 유효한 값은 scroll, fixed, and inherit 이 있다.

position 브라우저에게 배경 이미지의 위치를 알려 준다.

이미지는 적용된 HTML 요소의 경계 안의 어디에든 표시될 수 있다. 시각 효과 및 겹쳐서 보이게(layering) 하기 위해, background-position 를 사용하여 이미지를 정확하게 위치시킬 수 있다.

배경 위치, 키워드, 숫자 값을 표시하는 유용한 방법이 많이 있다. 키워드(topbottom) 는 유용하고 읽기 쉽다. 픽셀 값은 정확하지만. 높이와 폭을 변경할 수 없다. 마이너스 픽셀 값은 CSS 스프라이트를 사용할 때 유용하다. 나중에 알게 될 것이다.

퍼센트와 픽셀을 사용할 때, 시작점은 항상 HTML 요소의 왼쪽 상단 모서리이다. 하지만 픽셀과 퍼센트로 이미지 위치를 지정하는 방법은 다르다. Pixels always move the image a set number of pixels towards the bottom and right of the containing box (or towards the top and left if they are negative values), regardless of the size of the image and the containing box. Percentages, on the other hand, move the image a percentage of the difference between the containing box size, and the image size. If the image and the containing box are the same size, percentages will not move the image at all.

Valid values include length (generally in pixels), percentage (of the width of the element), and the keywords top, right, bottom, left, and center. Note that center can be used to indicate both vertical and horizontal center. Note also that you can mix percentages and pixels in rules, but not keywords and pixels or keywords and percentages.

background The shorthand property that can be used to describe all the other properties in one line.

Shorthand properties are very nifty indeed. Most developers use them to keep the CSS as lean as possible and group related properties. You can write a general rule using shorthand, and then override it as needed with specific properties.

The properties should always be indicated in the same order, to allow browsers to easily interpret the intended styles:

  1. color
  2. url
  3. repeat
  4. attachment (very rarely used; may be omitted)
  5. horizontal-position
  6. vertical-position

An example of this shorthand with all the properties used (except attachment) is as follows:

background: green url(logo.gif) no-repeat left top;

Building an alert message

Now that you understand the basic syntax involved, you can walk through the process of building up a complete alert box example, which demonstrates all the aspects of working with background images.

The design

Imagine a graphic designer has provided a visual mock-up of the alert message you want to create for your website. The alert has a light orange background color, to make it stand out from the surrounding paragraphs. It also has an alert icon ten pixels from the top left corner.

Note that the mockup has one line of text, but it might contain more in the future. One of the most important skills of the web developer is to anticipate how a design will evolve. Part of respecting the artistic vision for a site is thinking about consistency from launch to redesign. So the alert message could contain more than one line of text, or even multiple paragraphs, lists, or other HTML elements. Strive to be as element agnostic as possible. This will increase the likelihood of code reuse, and will enable you to set up the site to be as fast and efficient as it can be. The mockup looks like Figure 1.

Final mock up

Figure 1: The graphic designer’s mockup of the alert box.

The designer has also provided the icon we are meant to use, as shown in Figure 2.

Alert icon

Figure 2: The alert icon.

The code

Based on what you have learned about CSS backgrounds in the first part of this article, you may already be envisioning how to build this alert message. I encourage you to try building it now, and then compare your work against the example below.

After building your alert box, follow the step by step instructions below. Each screenshot links to code examples, so you can check out the source file at each stage. Experiment with the code, by increasing or decreasing values, and try out alternatives. You may also want to follow along, writing each new line of code in a tool such as Opera Dragonfly or Firefox Firebug, so you can immediately see the results of each step.

Creating the CSS hook, or selector.

First you need to create a class alert, that enable you to hook up the CSS code. Create new CSS and HTML skeleton files, link the CSS style sheet to the HTML file, and add the following code to each:

Copy the following CSS and paste it into the style sheet:

Copy the following HTML and paste it into the HTML document:

The code above styles the alert with a class, rather than an id, because that enables the possiblity for more than one alert in the page. For example, you may add alerts to a form element with several potential errors. The goal is to make your CSS as flexible as possible and constrain things to correspond to the design when building the HTML content.

At this point, you have a solid foundation in place, but the alert still looks like an ordinary paragraph because you have not yet added any styles. You will add some rules to style it next.

Note: I have intentionally chosen not to limit the class alert to paragraphs; alert boxes could easily contain other elements as well. You should leave as much flexibility as you can within your CSS.

Adding the background color

You already learned about using background color in text treatments in Text styling with CSS. The same principles apply to any HTML element and can be combined with background images to create visual effects. If the background color has neither been set nor inherited, it is, by default, transparent.

As shown below, you can add the light orange background color to the alert box to make it stand out from the text around it. It is important not to make the background color too dark, because you need to keep a reasonable level of contrast between the text and the background color. Add the following property inside the CSS rule:

The alert box now looks similar to Figure 3.

Code

Figure 3: An alert box with background color added.

Applying the background image

Next, you can add the background image to the alert. The path to the background image needs to be wrapped in url(), as shown in the code below. Add the highlighted line to the CSS rule:

The alert box now looks like Figure 4.

Code with background image

Figure 4: The background image has been added, but the tiling looks wrong.

Remember that each background property has a default value—if you have not specified a value, the default will be applied. Notice that the image is tiling over the entire alert, much like mosaic tiles on a kitchen floor. What is the takeaway? Background images are set to repeat both horizontally and vertically by default. Repeating backgrounds are particularly useful for gradients and patterns that fill the screen or a particular HTML element, but that effect is not desired in this case.

Controlling background repeat

Repeat horizontally and vertically

Figure 5: Much like the background image, these tiles repeat both horizontally and vertically.

Reading specifications can certainly be intimidating, but the specification is a really good place to figure out how CSS is supposed to work before you delve into the myriad browser differences. Read the colors and backgrounds portion of the W3C Specification and try to find the keyword to use when you do not want a background image to be repeated. This strategy is used in the example below:

Note that there is a section for each background property including background-repeat. Under Value, all of the possible choices are displayed, including; repeat, repeat-x, repeat-y, no-repeat, and inherit. By default (initial) background images are set to repeat. No direction is specified, which means that that the image will tile both horizontally and vertically. You have likely guessed that no-repeat is the value to set to prevent the image from tiling in either direction. Add the following highlighted line below to the CSS rule:

The alert box now looks like Figure 6.

Code for Step 4 background repeat

Figure 6: The alert box, with a single copy of the background image (with no tiling).

Additionally, you can choose to repeat in both directions (like kitchen tiles) or in either direction. Gradients often repeat horizontally or vertically (see Figure 7). You do not need to know the size of the HTML element; you simply cut a slice from your gradient and set it to repeat in the direction you want; either x for horizontal, or y for vertical. Patterns often repeat in both directions and icons usually do not repeat. You will explore background-repeat further in a later example.

repeat-x example

Figure 7: The greenish yellow tiles in this example repeat only horizontally.

Next, take a look at a practical example from my website. Review Figure 8.

A tiny image is tiled horizontally to create a three color design across the top of my website.

Figure 8: A repeating example from my website.

The CSS I used to add this decorative effect is relatively simple. I made the background repeat horizontally using repeat-x:

Attachment

The attachment attribute allows you to specify how the background behaves when the user scrolls down the page. The default behavior is scroll, which causes the background image to scroll along with the content.

On the other hand, setting background-attachment to fixed causes the element to be stuck to the browser window, so it stays in the same place when the content inside the element it is attached to is scrolled. This creates some odd effects, which will only be apparent when you scroll over the attached HTML element. The W3C uses it to mark the status of their specifications. For example, the “W3C Candidate Recommendation” image at top left. Scroll down the page and note that the image stays top left. It is attached to the body element, so it is always visible.

This step will have no effect on our display, because browsers set background images to scroll by default, but add it to the code anyway, to learn how the property is used. Add the highlighted line to the CSS rule:

As shown in Figure 9, the visual display of the alert box is not much different than it was before.

Code for background attachment

Figure 9: The display has not changed.

Positioning the image

Positioning is the fine tuning that enables you to place background images exactly where desired, both horizontally and vertically, within the HTML element. This property takes keyword and number values such as top, center, right, 100%, -10%, 50px and -30em.

Figure 10 shows the values you might use to place your background images in different positions.

Examples of possible background positions

Figure 10: Various examples of background position using keywords, percentages, and pixels.

The code below positions the background image. The goal is to position it in the top left corner, but not touching the sides, so you need to offset it by 10 pixels from both the top and left. This is accomplished by adding the following highlighted line to the CSS rule:

The first value is the horizontal offset, the second is the vertical. In this case the values are the same. After making these changes, your alert box should look like Figure 11.

Code with background position

Figure 11: Using CSS positioning to set the location of the background image.

Tip: Choose either keywords or number values, but do not combine them. Older browsers may ignore your declaration if you use both at once. Using right and bottom will achieve the same effect as using 100% horizontally or vertically, respectively.

Using shorthand to pull the whole thing together like a pro

As you have learned, certain CSS properties can be grouped together. Background and all of its sub-properties can be grouped in CSS rules. The CSS code described so far can be rewritten in a shortened form, as follows:

Tip: When grouping sub-properties of background, always put the properties in the following order. This is important for both cross-browser compatibility and style sheet organization and maintenance:

  1. color
  2. image
  3. repeat
  4. attachment
  5. horizontal position
  6. vertical position

Try replacing the old CSS code in your document with the shorthand shown above. After updating it, the example should look exactly the same (see Figure 12).

Finished product

Figure 12: The shorthand works like a charm!

Experimenting with the code

The best way to remember all the nuances of CSS is to test the options yourself. Try changing some of the properties in the example, and see how different values affects the display. Set the background-position to 100% 100%, and notice that it provides the same result as using the right and bottom keywords. What about if you change it to -5px 0? Why do you think part of the image is hidden?

Testing for quality

Testing is extremely important to providing a good user experience. Just because the site looks good on your machine with your specific configuration does not mean that it will look good in every browser. Follow these basic minimum steps when testing your alert box:

  • Increase or decrease the amount of text inside the alert.
  • Increase the text size in your browser at least two levels. Determine if it is better to use ems to position our image. Test what happens when you increase the text size.
  • Apply the class alert to other elements such as div, p, ul, strong, or em. How can you change the code to make the class agnostic?
  • Include several paragraphs and a list inside an alert div. Does the code still work?
  • Verify the alert visually in the Grade 1 browsers (also known as A-grade browsers). My advice is to write the code for good browsers and then adapt it for Internet Explorer–once the code works.

Rigorous testing is part of learning to write CSS. The more careful you are while learning, the faster you will be able to code.

Sprites

Users want it all. They want your site to be glamorous, interactive, and also fast. However, including large quantities of CSS background images can slow your site down considerably. The more HTTP requests you make, the slower your site will be (an HTTP request occurs whenever your computer is accessing a website and needs to ask the server to send it another asset in the site design, such as a CSS file or image… each additional request means a longer loading time for the site).

To get around this limitation, you can combine related icons into a single image, known as CSS Sprites. The background-position property allows you to then place the image in the appropriate positions so the icons display through the window of the HTML element that the CSS sprites are attached to.

In Figure 13, notice that to display the earth icon through the HTML window, you can place the image using left top. To move the position of the image so the alert icon is displayed, the background position needs to be changed to -80px 0. The negative horizontal value pulls the image to the left.

Only the part of the background image which is inside the HTML element is visible

Figure 13: Use CSS Sprites to reduce HTTP requests.

Note: If you set negative background positions, Safari will repeat your image, even if you’ve specified no-repeat. This is a consideration as you start working with background images to create more complicated layouts.

A complex sprite and background image example

Next, take a look at how you can leverage CSS sprites. Suppose a friendly designer sent us an new mockup. This one illustrates a list of links on the landing page of a blog. It points to the bloggers’ LinkedIn profile, RSS feed, Flickr photos, and bookmarks. As you evaluate each link, notice that there is a gradient starting in the center as white and transitioning to gray at the top and bottom of the link. And to further complicate things, the designer asked if we could make each link plain white with no curve when visitors hover over the link, as shown in Figure 14.

List mockup

Figure 14: The new design mockup.

The logos could be included using img elements in the markup. However, using CSS sprites is a much better solution. The sprites load faster because only one image must load (not four), and it declutters your HTML, by reducing the amount of markup needed.

Creating the sprite

The first step involves cutting out the four logos and creating the sprite set, as shown in Figure 15.

Logos sprite

Figure 15: The sprite set.

You also need to cut out a 1 pixel wide slice of the gradient. For the sake of visibility, I have cut out a slightly larger slice, but in a real-world site project you only need a one pixel image (see Figure 16).

Gradient background

Figure 16: The slice used for the gradient background.

The HTML that creates the list is an unordered list containing links. Note the empty span elements inside the links. It is very important not to have fixed height and width on elements that contain text. After all, you have no idea how large the text will be. What happens if the site is translated to German? You can use these extra spans to display the logos. As an alternative, you may decide that you do not want to have extraneous non-semantic markup cluttering up your HTML. In this case, you will need to use a larger sprite and leave white space between the icons. Keep in mind that this strategy is slower for users on slow connections, especially those using mobile phones to view the site. The code for the list is shown below. Copy it and then paste it into an HTML document:

The CSS utilizes both background images. First, take a look at the gradient background image. There are three interesting things to notice:

  1. The image repeats horizontally (repeat-x.) This tiling enables you to make such a small image spread across the entire list.
  2. The image is centered vertically. You want the round bit of the image to appear in the middle of the list item, so you should use a background position of left center.
  3. In the CSS, I’ve applied a background color that is the same gray as the gray in the gradient image. This ensures, if the element grows, it will not look broken. For more information about this kind of technique, I recommend reading Bulletproof Web Design by Dan Cederholm.

Add the following CSS to a new CSS file, and link it to the HTML document:

The last line means that the element should not display a background color or image when the visitor hovers their cursor over it, or focuses on the element using the keyboard. You may be wondering why I applied the background properties to the link rather than the list item. The answer is that Internet Explorer 6 and earlier do not support pseudo classes like hover on elements other than links. I’ve made the adjustment in the code to accommodate this constraint.

Next you can create the CSS for the little logos. As usual, you can start by defining the most general case for all span elements within your navigation module. It is here that you define the image to be used by all spans, the repeat setting, and the background position (each is different, so you can use the first one). You can use shorthand for this rule. Note that CSS comments divide the sections of our code into manageable chunks. Add the following code to the bottom of the CSS file:

With the basic formatting completed, you can now define the exceptions, or what is different about each specific logo. In this case, the only CSS that changes is the background-position. Each respective list item needs to have the image moved 15 pixels more to the left, because each of the logo images are 15 pixels wide. Add the following to the bottom of the CSS file:

This example might seem intimidating at first. Keep your focus on the background images. In this case, using a negative pixel value pulls the background image left, so that the relevant part of the image is displayed. Positive values move the background image down and right, while negative values pull the image up and to the left.

Experiment with the background position values in the finished example, to better understand how to adjust sprite positioning.

See also

External resources

Image credits

Exercise Questions

  • A paragraph is 40px by 180px and your background image is 60px by 200px. Will you see the entire image or only part of it? Why?
  • You want an image to be positioned in the bottom left corner of the blockquote element—please fill in the correct values.
  • Say you wanted each h2 in your document with a class of “question” to have a gradient pattern applied. Would you use repeat-x, repeat-y, no-repeat, or repeat to achieve something similar to the example below? Why?

logos sprite

  • What would be the background position of the example in question number 3? How could you creatively use a background colour to be sure the background could expand to any height? Why is this important?
  • What shorthand can you use to remove all background properties?
  • What is the purpose of CSS sprites?

답글 남기기