Web design css background

CSS Backgrounds

The CSS background properties are used to add background effects for elements.

In these chapters, you will learn about the following CSS background properties:

  • background-color
  • background-image
  • background-repeat
  • background-attachment
  • background-position
  • background (shorthand property)

CSS background-color

The background-color property specifies the background color of an element.

Example

The background color of a page is set like this:

With CSS, a color is most often specified by:

  • a valid color name — like «red»
  • a HEX value — like «#ff0000»
  • an RGB value — like «rgb(255,0,0)»

Look at CSS Color Values for a complete list of possible color values.

Other Elements

You can set the background color for any HTML elements:

Example

Here, the ,

, and elements will have different background colors:

div background-color: lightblue;
>

Opacity / Transparency

The opacity property specifies the opacity/transparency of an element. It can take a value from 0.0 — 1.0. The lower value, the more transparent:

Example

Note: When using the opacity property to add transparency to the background of an element, all of its child elements inherit the same transparency. This can make the text inside a fully transparent element hard to read.

Transparency using RGBA

If you do not want to apply opacity to child elements, like in our example above, use RGBA color values. The following example sets the opacity for the background color and not the text:

You learned from our CSS Colors Chapter, that you can use RGB as a color value. In addition to RGB, you can use an RGB color value with an alpha channel (RGBA) — which specifies the opacity for a color.

An RGBA color value is specified with: rgba(red, green, blue, alpha). The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque).

Tip: You will learn more about RGBA Colors in our CSS Colors Chapter.

Example

The CSS Background Color Property

Источник

background

The background shorthand CSS property sets all background style properties at once, such as color, image, origin and size, or repeat method. Component properties not set in the background shorthand property value declaration are set to their default values.

Читайте также:  Bitrix epilog after php

Try it

Constituent properties

This property is a shorthand for the following CSS properties:

Syntax

/* Using a */ background: green; /* Using a and */ background: url("test.jpg") repeat-y; /* Using a and */ background: border-box red; /* A single image, centered and scaled */ background: no-repeat center/80% url("../img/image.png"); /* Global values */ background: inherit; background: initial; background: revert; background: revert-layer; background: unset; 

The background property is specified as one or more background layers, separated by commas.

The syntax of each layer is as follows:

  • Each layer may include zero or one occurrences of any of the following values:
    • The value may only be included immediately after , separated with the ‘/’ character, like this: » center/80% «.
    • The value may be included zero, one, or two times. If included once, it sets both background-origin and background-clip . If it is included twice, the first occurrence sets background-origin , and the second sets background-clip .
    • The value may only be included in the last layer specified.

    Values

    See background-clip and background-origin . Default: border-box and padding-box respectively.

    See background-color . Default: transparent .

    The following three lines of CSS are equivalent:

    background: none; background: transparent; background: repeat scroll 0% 0% / auto padding-box border-box none transparent; 

    Accessibility concerns

    Browsers do not provide any special information on background images to assistive technology. This is important primarily for screen readers, as a screen reader will not announce its presence and therefore convey nothing to its users. If the image contains information critical to understanding the page’s overall purpose, it is better to describe it semantically in the document.

    Formal definition

    • background-image : none
    • background-position : 0% 0%
    • background-size : auto auto
    • background-repeat : repeat
    • background-origin : padding-box
    • background-clip : border-box
    • background-attachment : scroll
    • background-color : transparent
    • background-position : refer to the size of the background positioning area minus size of background image; size refers to the width for horizontal offsets and to the height for vertical offsets
    • background-size : relative to the background positioning area
    • background-image : as specified, but with url() values made absolute
    • background-position : as each of the properties of the shorthand:
      • background-position-x : A list, each item consisting of: an offset given as a combination of an absolute length and a percentage, plus an origin keyword
      • background-position-y : A list, each item consisting of: an offset given as a combination of an absolute length and a percentage, plus an origin keyword
      • background-color : a color
      • background-image : discrete
      • background-clip : a repeatable list of
      • background-position : a repeatable list of
      • background-size : a repeatable list of
      • background-repeat : discrete
      • background-attachment : discrete

      Formal syntax

      background =
      [ # , ]?

      =
      ||
      [ / ]? ||
      ||
      ||
      ||

      =
      ||
      ||
      [ / ]? ||
      ||
      ||
      ||

      =
      |
      none

      =
      [ left | center | right | top | bottom | ] |
      [ left | center | right | ] [ top | center | bottom | ] |
      [ center | [ left | right ] ? ] && [ center | [ top | bottom ] ? ]

      =
      [ | auto ] |
      cover |
      contain

      =
      repeat-x |
      repeat-y |
      [ repeat | space | round | no-repeat ]

      =
      scroll |
      fixed |
      local

      =
      border-box |
      padding-box |
      content-box

      =
      |

      =
      |

      =
      url( * ) |
      src( * )

      Examples

      Setting backgrounds with color keywords and images

      HTML

      p class="topbanner"> Starry skybr /> Twinkle twinklebr /> Starry sky p> p class="warning">Here is a paragraphp> p>p> 

      CSS

      .warning  background: pink; > .topbanner  background: url("starsolid.gif") #99f repeat-y fixed; > 

      Result

      Specifications

      Browser compatibility

      BCD tables only load in the browser

      See also

      Found a content problem with this page?

      This page was last modified on Jul 18, 2023 by MDN contributors.

      Your blueprint for a better internet.

      MDN

      Support

      Our communities

      Developers

      Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
      Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

      Источник

      Фон для сайта (свойство CSS background)

      Фон для сайта (свойство CSS background)

      Если вы заметили, слегка приукрасил Дизайн Манию, добавил текстуры в фон. Сразу же появилась идея рассказать вам как именно мне удалось это сделать. Открываю данным постом рубрику «Верстка» раздела «Веб-дизайн». В данной категории планирую публиковать статьи, заметки, рекомендации и уроки по HTML, CSS, а также, возможно, JavaScript. Материал постараюсь размещать простой и с пояснениями, чтобы понятно было всем читателям. Думаю, подобная информация пригодится многим блоггерам, которые хотят, но не могут подправить собственные дизайны из-за отсутствия навыков верстки.

      Итак, с помощью свойства background можно установить цвет, положение, изображение, привязку и повторяемость бекграунда как для отдельного элемента, так и для всего сайта. Последнее, по сути, является заданиям настроек для тэга body. Рассмотрим все свойства, связанные с фоном (background). Если вы только учитесь, то самым лучшим вариантом усвоения урока будет практическое применение свойства в таком же порядке, как я рассматриваю ниже:

      Background-color

      Задает цвет фона. Можно применять к отдельным элементам ,

      или ко всему сайту через через тэг :

      /* черный фон сайта */ body { background-color: #000; } /* черный фон заголовка, белый цвет шрифта */ h1 { color: #fff; background-color: #000; }

      /* черный фон сайта */ body < background-color: #000; >/* черный фон заголовка, белый цвет шрифта */ h1

      Background-image

      Используется для вставки фонового изображения, при этом в css указываем ссылку на картинку:

      body { background-color: #000; background-image: url ("my-image.jpg"); }

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

      Background-size

      Определяет размер фонового изображения.

      div { background: url(my-image.jpg); background-size: 100% 100%; background-repeat: no-repeat; }

      Для свойства есть несколько интересных особенностей. Кроме числовых значений размеров (px,pt) можно использовать процентные или автоматическое вычисление (auto — например для одной из стороны картинки — 500px auto). Данное свойство применяется для создания фона для сайта с картинкой на весь экран.

      Если указать значение cover, то фон будет масштабироваться дабы ширина и высота картинки = ширине и высоте блока. Если использовать значение contain, то масштабирование будет с сохранением пропорций чтобы изображение полностью поместилось в блок.

      Background-repeat

      Используемое в предыдущем примере изображение будет «растиражировано» (повторяется) по всему экрану. Данное свойство призвано управлять этим процессом. Имеется несколько допустимых значений:

      • background-repeat: repeat-x — изображение повторяется только по горизонтали
      • background-repeat: repeat-y — изображение повторяется только по вертикали
      • background-repeat: repeat — изображение повторяется по горизонтали и вертикали
      • background-repeat: no-repeat — изображение не повторяется

      background-attachment — данное свойство определяет будет ли фоновое изображение фиксироваться при прокрутке страницы:

      • background-attachment: scroll — прокручивается вместе со страницей
      • background-attachment: fixed — при прокрутке фон остается неподвижным

      Background-position

      Задает расположения рисунка относительно экрана, по умолчанию оно выводится в левом верхнем углу. Значение этого свойства представляет собой набор координат Х (по горизонтали) и Y (по вертикали), которые начинаються с левого верхнего угла. Может задаваться:

      • в фиксированных единицах (пикселы, сантиметры)
      • в процентах
      • словесно: — top (сверху), bottom (снизу), center (по центру), left (слева) и right (справа).
      • background-position: 20px 50px — изображение отступает вниз на 20 пикселей сверху и вправо на 50 от левого края.
      • background-position: 50% 25% — расположено по центру по горизонтали и отступает на 25% сверху.
      • background-position: right bottom — рисунок располагается снизу справа.

      Все эти настройки могут быть записаны в одном свойстве background, порядок следования свойств:

      [background-color] | [background-image] | [background-repeat] | [background-attachment] | [background-position]
      background: #000 url("my-image.jpg") no-repeat fixed left bottom;

      background: #000 url(«my-image.jpg») no-repeat fixed left bottom;

      Если какое-то свойство пропускается, то его значение установлено по умолчанию.

      Надеюсь, данный урок вам пригодился, подписываемся на обновления блоге через RSS, дальше вас ожидает еще много интересных секретов!

      Источник

Оцените статью