Css как поставить картинку на фон

от admin

CSS background images

Admit it! Since the first article in the Web Standards Curriculum, you’ve been itching to learn how to make your site look fierce and fabulous. Maybe you even skipped ahead to this section?

Background images are all about making your site look sexy, but you might be surprised how closely they build upon the fundamental concepts you have already learned.

As you already learned earlier on in the course, one of the most important changes that comes with CSS was the ability to separate presentation, or the way things look, from semantics, or what things mean. The CSS background image is among the most important tools you have at your disposal, because it lets you apply decorative images to particular parts of your HTML without adding any extra weight to your HTML. Previously, authors (that’s you!) were forced to fill their code with img tags.

CSS and in particular the background property keep your HTML free from presentational clutter. Redesigns and other transitions, in the life of sites built with modern methods, can then be completed much more smoothly. You’ll be able to update your entire site by changing only the style sheet, rather than recoding every HTML page. Depending on the size of your site, this can be a substantial saving.

In this article I’ll show the basics of how CSS background images work, including applying a background image via CSS, adjusting its placement, tiling it vertically or horizontally and combining background images using CSS Sprites to improve site performance.

How does it work?

The CSS for backgrounds is split into several different properties. Using these properties, such as position and color , you can begin to control the look and feel of your page. In this article, you will go through CSS background images in detail, building an alert message as an example, step by step.

First, let’s learn a little more about the different properties at our disposal.

Background Properties

There are several ways to indicate background-color , including RGB values and keywords. Most people use hexadecimal notation, a pound/hash symbol (#) followed by six characters. The first pair indicates the red levels, and the second and third indicate the green and blue levels respectively— #RRGGBB .

Many colour picker tools will help you find the hexadecimal notation of a given colour. Pure red, for example would be #FF0000.

Valid values include a color value, transparent , or inherit .

Set the background-image by showing the browser where to find the image, using the URL. For example; url(alert.png) . Note that the path is prefaced with they keyword url and wrapped in parenthesis. This syntax is important to the browser understanding that you mean to indicate a location.

Valid values include a URL , none , or inherit .

Images can be tiled vertically, horizontally, or both, to fill the entire width or height of an HTML element. Use background-repeat to instruct the browser to repeat a background image.

Valid values include repeat , repeat-x , repeat-y , and no-repeat .

Images can either scroll with their content, or stay fixed in place in the view screen. Valid values include scroll , fixed , and inherit .

Images can be displayed anywhere within the borders of the HTML element on which they are applied. Use background-position to precisely place your images for visual effect and layering.

There are many useful ways to indicate background position, keywords and numeric values. Keywords (such as top and bottom ) are very useful and easy to read. Pixel values are very precise, but don’t adapt to changing heights and widths. Negative pixel values are useful when using CSS sprites, as you’ll find out later.

When percentages and pixels are used, the starting point is always the top left corner of the HTML element, although the way image positioning works with pixels and percentages is rather different. 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 won’t 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.

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 I’ve gone through the basic syntax involved, I’ll walk you through building up a complete alert box example, which will demonstrate all the aspects of background images.

The design

Let’s say a graphic designer has provided a visual mock-up of the alert message you want to create for your web site. Looking at the alert you see that the background is light orange, setting it off 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. You should try to be as element agnostic as possible. This will increase the likelihood of code reuse, and 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 our 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 thinking about how to build this alert message. I’d like to encourage you to have a go at it now, and then compare your work against my example.

Ok—had a try? Now let’s go through it step by step. Each screen shot links to code examples, so you can check out the source at each stage. Experiment with the code, increase or decrease 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 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 , for the CSS to hook on to. Create new CSS and HTML skeleton files, link the CSS to the HTML file, and add the following code to them:

Here I am styling the alert with a class , rather than an id , because I could have more than one alert in the page, for example a form element with several errors. You want to make your CSS as flexible as possible and constrain things to correspond to the design when building the HTML.

Ok, so you’ve put a solid foundation in place, but it still looks like an ordinary paragraph because you haven’t yet added any styles. Lets do that 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 colour

You already learned about using background colour 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 colour has neither been set nor inherited, it is, by default, transparent.

Let’s add the light orange background colour to the alert box to make it stand out from the text around it. You don’t want it to be too dark because it is important that you keep a reasonable level of contrast between the text and the background colour. Add the following property inside your CSS rule

The Alert box should now look more like Figure 3.

Figure 3: An alert box with background colour added.

Applying the background image

Now let’s add the 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 will now look like Figure 4.

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

Remember that each background property has a default value—if you haven’t specified a value, the default will be applied. Of course, you will have noticed that the image is tiling over our 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 our 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. Go take a look at the colors and backgrounds portion of the W3C Specification and try to find the keyword to use when you don’t want a background image to be repeated. We’ll use that in our example below.

Found it? Note that there is a section for each background property including background-repeat. Under Value, you’ll see all the possible choices 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 most likely guessed that no-repeat is the value you are looking for to prevent the image from tiling in either direction. Add the following highlighted line to the CSS rule.

The alert box will now look like Figure 6.

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

Additionally, you can choose to repeat in both directions (like kitchen tiles) or neither direction. Gradients often repeat horizontally or vertically (see Figure 7). You don’t 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.

Let’s take a look at a practical example from my website—look at Figure 8.

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

Figure 8: A repeating example from my own web site.

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

Attachment

attachment allows you to specify how the background behaves when the user scrolls down the page. The default behaviour 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 HTML element it is attached to. 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 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 let’s add it to the code anyway so that you can see 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 to how it was before.

Figure 9: Not much different here.

Positioning the image

Positioning is the fine tuning that lets you place your background image exactly where you want it to be, 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.

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

So let’s position the background image. You want it to be 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 can be done by adding the following highlighted line to the CSS rule. Do this now.

The first value is the horizontal offset, the second is the vertical. In this case they are the same. Your alert box should now look like Figure 11.

Figure 11: Using positioning to place the background image.

Tip: Stick to either keywords or number values—older browsers may ignore your declaration if you use both at once. Using right and bottom will achieve the same thing as 100% horizontally or vertically, respectively.

Using shorthand to pull the whole thing together like a pro

As you have already seen, certain CSS properties can be grouped together. Background and all of its sub properties are among them. The CSS code we’ve written so far can be rewritten in 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 stylesheet organisation and maintenance:

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

Try replacing the old CSS with the shorthand shown above, and your example should look exactly the same—see Figure 12.

Figure 12: The shorthand works like a charm!

Experimenting with the code

The best way to remember all the nuances of CSS is to try out the options yourself—try changing some of the properties in the example, and see how that affects it. Set the background-position to 100% 100% , and notice that it gives the same result as using the right and bottom keywords. What about if you change it to -5px 0 ? Why do you think you now can’t see part of the image?

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 doesn’t mean that it will look good for everyone. You should 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. Would it have been better to use ems to position our image? Then what happens when you increase the text size?
  • Apply the class alert to other elements such as div , p , ul , strong , or em . What do you need to change 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). My advice is to write for good browsers and adapt 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 become.

Sprites

Users want it all. They want your site to be glamorous, interactive, and also fast, however including large numbers 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 is when your computer is accessing a web site and needs to ask the server to send it another asset that makes up the site, 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 the CSS sprites are attached to.

For example in Figure 13, you will see 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.

Figure 13: Using CSS Sprites to reduce HTTP requests.

Note: If you use negative background positions, Safari will repeat your image, even if you’ve specified no-repeat . This is something to keep in mind as you start playing with background images to create more complicated layouts.

A complex sprite and background image example

Let’s have a look at how CSS sprites can be used to good effect. Suppose our friendly designer sent us an new mockup. This one is for a list of links on the landing page of a blog. It points to the bloggers’ LinkedIn profile, RSS feed, Flickr photos, and bookmarks. Looking at each link, we realize that there is a gradient starting in the center as white and going 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—check out Figure 14.

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 way to go—the sprites load faster as only one image needs to be loaded (not four), and it declutters your HTML, reducing the amount of markup needed.

Creating the Sprite

The first step is to cut out the four logos and create the sprite set, as seen in Figure 15.

Figure 15: The sprite set.

You also need to cut out a 1 pixel wide slice of our gradient. For the sake of visibility, I have cut out a slightly larger slice, but you only need one pixel—see Figure 16.

gradient bkg

Figure 16: The slice for our gradient background.

The HTML for 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 gets translated to German? You can use these extra spans to display the logos. As an alternative, you may decide that you don’t 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 will be slower for users on slow connections, especially those on mobile phones. The code for the list looks like so—add this to an HTML template:

Читать:
Как найти точку пересечения прямой и окружности

The CSS makes use of both background images. First, take a look at the gradient background image. There are three interesting things to note about it:

  1. The first is that the image repeats horizontally ( repeat-x .) This is how we are able to make such a small image spread across the entire list.
  2. The second is that the image is centred 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. Finally, in the CSS I’ve applied a background colour that is the same grey as the grey in our gradient image. In this way, if the element grows, it won’t look broken. For more information about this kind of technique I recommend Bulletproof Web Design by Dan Cederholm.

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

The last line means that the element should have no background colour or image when the user hovers using the mouse, or focuses using the keyboard. Perhaps you are 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 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, and the background position (each is different, so lets use the first). You can use shorthand for this rule. Note that I’m using CSS comments to divide sections of our code into manageable chunks. Add the following code to the bottom of the CSS file:

With the general case well in hand, 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 pulled 15 pixels more to the left, because each of the logos 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, I’ve used negative pixel values to pull the background image left so that the relevant part of the image is seen. Positive values push the background image down and right, negative values pull the image up and left.

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

Summary

You should now understand CSS background images, and what’s more, you are becoming more comfortable reading specifications, so if you have doubts about a particular property, you should know how to go look it up. This article covered background colour, image, repeat, attachment, and position. You also learned why developers use CSS Sprites, and how to use this advanced technique.

Image credits

    , by DimsumDarren , by emdot

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?

  • 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?

Further reading

Note: This material was originally published as part of the Opera Web Standards Curriculum, available as 31: CSS background images, written by Nicole Sullivan. Like the original, it is published under the Creative Commons Attribution, Non Commercial — Share Alike 2.5 license.

Как сделать картинку фоном в HTML и CSS. 3 простых способа

Приветствую. В этой статье я хочу рассказать о трех способах размещения изображения в качестве фона всей страницы при помощи только HTML + CSS (без использования JS).

Итак, требования к фоновому изображению у нас следующие:

  • Покрывается 100% ширины и высоты страницы
  • Фон масштабируется при необходимости (background растягивается или сжимается в зависимости от размеров экрана)
  • Сохраняются пропорции картинки (aspect ratio)
  • Изображение центрировано на странице
  • Фон не вызывает скроллов
  • Решение максимально кроссбраузерное
  • Не используются никакие другие технологии кроме CSS

design-development-electronics-326424.jpg

Способ 1

На мой взгляд, это лучший способ, ведь он самый простой, лаконичный и современный. Он использует свойство CSS3 background-size , которое мы применяем к тегу html . Именно html , а не body , т.к. его высота больше или равна высоте окна браузера.

Устанавливаем фиксированный и центрированный фон, затем корректируем его размер, используя background-size: cover .

Этот способ работает в

Chrome (любая версия) Opera 10+ Firefox 3.6+ Safari 3+ IE 9+

Способ 2

В случае если ширина окна будет меньше ширины изображения, будет использоваться media query для выравнивания бэкграунда по центру.

Этот способ работает в:

  • Любой версии хороших браузеров (Chrome, Opera, Firefox, Safari)
  • IE 9+

Способ 3

Еще один способ заключается в следующем: фиксируем изображение <img /> к левому верхнему углу страницы и растягиваем его при помощи свойств min-width и min-height 100%, сохраняя при этом соотношение сторон.

Правда при таком подходе картинка не центрируется. Но эта проблема решается заворачиванием картинки в <div />, который мы делаем в 2 раза больше размера окна. А само изображение мы растягиваем и помещаем по центру.

Этот способ работает в хороших браузерах и IE 8+.

Надеюсь, эта информация будет для Вас полезной. Лично я частенько пользуюсь этими методами, особенно первым. Наверняка есть и другие способы поместить изображение на задний фон при помощи CSS. Если Вы о них знаете, поделитесь, пожалуйста, комментариях.

background-image

Свойство CSS background-image устанавливает одно или несколько фоновых изображений для элемента. Изображения рисуются в слоях контекстов наложения одно поверх другого. Первый слой выводится так, чтобы он был ближе всего к пользователю.

Границы border элемента затем рисуются поверх них, и background-color рисуется под ними. То, как изображения отрисовываются относительно рамки и её границ, определяется CSS-свойствами background-clip и background-origin .

Если указанное изображение не может быть нарисовано (например, когда файл, определённый указанным URI, не может быть загружен), браузеры обрабатывают его так, как если бы оно было значением none .

Примечание: Даже, если изображение непрозрачно и цвет не будет показан при нормальных обстоятельствах, веб-разработчику следует всегда указывать атрибут background-color . Если изображение не может быть загружено —например, в случае отказа сетевого подключения — у элемента будет отображён цветной фон.

Начальное значение none
Применяется к все элементы. Это также применяется к ::first-letter и ::first-line .
Наследуется нет
Обработка значения как указано, но с абсолютными значениями url
Animation type discrete

Синтаксис

Значения

Это ключевое слово обозначает отсутствие изображений.

<image> (en-US) обозначает изображение для отображения. Их может быть несколько, разделённых запятыми, поскольку поддерживаетсянесколько фонов (en-US) .

Официальный синтаксис

Примеры

Несколько фонов и прозрачность

Обратите внимание, что изображение звезды частично прозрачно и наложено на изображение кошки.

Backgrounds

In this module learn the ways you can style backgrounds of boxes using CSS.

Backgrounds #

Behind every CSS box is a specialized layer called the background layer. CSS provides a variety of ways to make meaningful changes to it–including allowing multiple backgrounds.

Background layers are furthest from the user, rendered behind the contents of a box starting from its padding-box region. This enables the background layer to not overlap with borders at all.

Background color #

One of the simplest effects you can apply to a background layer is setting the color. The initial value of background-color is transparent , which allows the contents of a parent to be visible. A valid color set on a background layer sits behind other things painted on that element.

Background images #

  • An image URL or data URI using the url CSS function.
  • An image dynamically created by a gradient CSS function.

Setting a background-image with the url CSS function #

CSS gradient backgrounds #

Several gradient CSS functions exist to allow you to generate a background-image, when passed two or more colors.

Regardless of which gradient function is used, the resulting image is intrinsically sized to match the amount of space available.

Demo showing example of applying a background-image using gradient functions:

Repeating background images #

By default, background images repeat horizontally and vertically to fill the entire space of the background layer.

  • repeat : The image repeats within the space available, cropping as necessary.
  • round : The image repeats horizontally and vertically to fit as many instances into the space available, without cropping, compressing, or stretching it.
  • space : The image repeats horizontally and vertically to fit as many instances within the space available without cropping—spacing out instances of the image as needed. Repeating images touch the edges of the space a background layer occupies, with white space evenly distributed between them.

The background-repeat property allows you to set the behavior for the x and y axis independently. The first parameter sets the horizontal repeat behavior, and the second parameter sets the vertical repeat behavior.

If you use a single value, it will be applied to both the horizontal and vertical repeats.

The shorthand also has convenient one-word options to make your intent clearer.

The value repeat-x repeats an image only horizontally; this is equivalent to repeat no-repeat .

The following demo demonstrates these capabilities of the background-repeat property:

Background position #

You may have noticed when some images on the Web are styled with a background-repeat: no-repeat declaration, such images are displayed top left of their container.

The initial position of background images is top left. The background-position property allows you to change this behavior by offsetting the image position.

As with background-repeat , the background-position property allows you to position images along the x and y axis independently with two values by default.

When CSS lengths and percentages are used, the first parameter corresponds to the horizontal axis while the second parameter corresponds to the vertical axis.

When keywords are only used the order of the keywords does not matter:

Order does not matter for keywords associated with different axes of position.

When CSS values are used alongside keywords, the order matters. The first value represents the horizontal axis and the second the vertical axis.

You cannot use keywords associated with the same axis simultaneously.

The background-position property also has a convenient one value shorthand; the omitted value resolves to 50% . Here’s an example that demonstrates this using the keywords the background-position property accepts:

In addition to its default two parameter form and one parameter form; the background-position property also accepts up to four parameters;

When three or four parameters are used, a CSS length or percentage must be preceded by the top , left , right , or bottom keywords in order for the browser to calculate which edge of the CSS box the offset should originate from.

When three parameters are used, a CSS length or value can be the second or third parameter with the other two being keywords; the keyword it succeeds will be used to determine the edge the CSS length or value corresponds to being the offset of. The offset of the other keyword specified is set to 0.

CSS length value must be preceded by the top , right , bottom , or left keywords when using three or more parameters.

CSS length value must be preceded by the top , right , bottom , or left keywords when using three or more parameters.

If background-position: top left 20% is applied to a CSS background image, the image is placed at the top of the box, the 20% value represents a 20% offset from the left of the box (on the x axis).

If background-position: top 20% left is applied to a CSS background image, the 20% value represents a 20% offset from the top of the CSS box (on the y axis), and the image is placed at the left of the box.

When four parameters are used, the two keywords are paired with two values corresponding to an offset against the origins of each keyword specified. If background-position: bottom 20% right 30% is applied to a background-image, the background-image is positioned 20% from the bottom, and 30% from the right of the CSS box.

The following demo demonstrates this behavior:

Here are more examples of using the background-position property using a mix of CSS and keyword values:

Background Size #

The background-size property sets the size of background images; By default background images are sized based on their intrinsic (actual) width, height, and aspect ratio.

The background-size property uses CSS length and percentage values or specific keywords. The property accepts up to two parameters corresponding to allowing you to change width and height of a background independently.

  • auto : When used independently, the background image is sized based on its intrinsic width and height; when auto is used alongside another CSS value for the width (first parameter) or height (second parameter), the dimension set to auto is sized as needed to maintain the natural aspect ratio of the image. This is the default behavior of the background-size property.
  • cover : Covers the entire area of the background layer. This may mean the image is stretched or cropped.
  • contain : Sizes the image to fill the space without stretching or cropping. As a result, empty space can remain that will cause the image to repeat, unless background-repeat is set to no-repeat .

The latter 2 are intended to be used in a standalone fashion without another parameter.

The following demo demonstrates these keywords in action:

Demo demonstrating applying these keywords to background-size :

Background attachment #

The background-attachment property enables you to modify the fixed position behavior of background images (images part of a background layer) once the layer is visible on a screen.

It accepts 3 keywords: scroll , fixed , and local .

The default behavior of the background-attachment property is the initial value of scroll . When more space is needed, the images move with that space within the background layer determined by the bounds of the CSS box.

Using the value fixed fixes the position of background images to the viewport.

Once the space of the background layer images originally takes up needs to be scrolled (or rendered) offscreen, images within the background layer stay fixed in the original position the background layer enabled them to be until the entire layer is scrolled off screen by the viewport.

The local keyword enables the position of background images to be fixed relative to the element’s contents. Background images now move along the space they occupy as that space renders inside and outside the bounds of the CSS box (usually due to scrolling, 2D, or 3D transformations).

Background origin #

The background-origin property enables you to modify the area of backgrounds associated with a particular box. The values the property accepts correspond to the border-box , padding-box , and content-box regions of a box .

Try these options out using the following demo:

Background clip #

The background-clip property controls what is visually seen from a background layer regardless of the bounds created by the background-origin property.

Like background-origin the regions that can be specified are border-box , padding-box , and content-box corresponding to where a CSS background layer can be rendered. When these keywords are used, any rendering of the background further than the region specified will be cropped or clipped.

The background-clip property also accepts a text keyword that clips the background to be no further than the text within the content box. For this effect to be evident in the actual text within a CSS box, the text must be partially or completely transparent.

A relatively new property, at the time of this writing, Chrome and most browsers require the -webkit- prefix to use this property.

Gotchas

Multiple backgrounds #

As mentioned at the beginning of the module, the background layer allows multiple sublayers to be defined. For brevity, I’ll refer to these sublayers as backgrounds.

Multiple backgrounds are defined top to bottom; The first background is the closest to the user, while the last background is the furthest from the user.

The only background defined or the last layer is designated the final background layer by the browser. Only this layer is allowed to assign a background-color .

Multiple layers can be individually configured using most background-related CSS properties that are comma separated, as demonstrated in the code snippet and live demo below.

The background shorthand #

To make it easier to style the background layer of a box-especially when multiple background layers are desired–there is a shorthand that follows the following specific pattern:

Gotchas

Order is important in the shorthand form of declaring multiple backgrounds. The position and size values must both be provided, separated by a slash ( / ). Declaring the origin and clip behavior in the correct order allows you take advantage of setting keywords that are valid for both simultaneously

The following declaration clips the background, and originates it from the content box:

With these shorthand semantics in mind, the previous background-related declarations of the code snippet could be rewritten to be following:

Background images are positioned in the top-left of a CSS box.

Depending on its intrinsic size an image may appear to not be in positioned in the top left corner of a CSS box, background-position needs to be explicitly used to change the default position of a background image.

Background images are not repeated by default.

background-repeat: no-repeat explicitly must be used to not repeat a background-image. Additionally background-repeat: repeat-x and background-repeat: repeat-y can be used to prevent repeating in the specific axis.

Which of the following background-position declarations are valid?

background-position: 50% left background-position: top right 33% background-position: right bottom background-position: left

When CSS values are used with keywords, the order of the values matters.

This positions a background image to the very top of a box and 33% from the right edge of the box.

This positions a background image to the very right and bottom of a box. Position of differing axes can be named in any order.

This positions a background image to be at the very left of the box and centered vertically. When just one position of an axis is provided, the background image is centered in the opposite axis.

Demonstration of the use of CSS Clip

What would be the steps to render a background like this against its content?

  1. Use background-clip: text . Check if the property is supported in the browsers you need to support.
  2. Use background-image: url(/texture.jpg) .
  3. Use -webkit-text-fill-color: transparent or semi-transparent for the background image to be seen within the text.

To set a background image to be fixed within a viewport you use:

background-position: fixed background-fixed-to-viewport: true background-attachment: fixed background-attachment: scroll

‘This is an invalid value for the background-position property.’

background-fixed-to-viewport doesn’t exist in CSS yet.

background-attachment: fixed explicitly sets the background image to be fixed within the current viewport.

‘ background-attachment is the property to use to set a background image to be fixed within a viewport; however scroll is the default value for the property that fixes the background image by default to the box unimpacted by the content within the box.’

The default background-origin of a background within a CSS box is:

content-box border-box padding-box margin-box

Valid value for background-origin , but isn’t the default.

Valid value for background-origin , and it’s pre-arranged borders can be painted on top of backgrounds, but isn’t the default.

The default value for background-origin . Allows the background to be rendered beyond the content and up to the border of a box.

While a recognized region of a CSS box, it is an invalid value for the background-origin property.

Next and previous lessons

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies.

Похожие статьи