background-position

background-position

Задает начальное положение фонового изображения, установленного с помощью свойства background-image . В CSS3 допустимо указывать несколько значений для каждого фона, перечисляя значения через запятую.

Синтаксис

background-position: [left | center | right | | ] || [top | center | bottom | | ] | inherit

= [left | center | right | | ] || [top | center | bottom | | ] | inherit.

Значения

У свойства background-position два значения, положение по горизонтали (может быть — left , center , right ) и вертикали (может быть — top , center , bottom ). Кроме использования ключевых слов положение также можно задавать в процентах, пикселах или других единицах. Если применяются ключевые слова, то порядок их следования не имеет значения, при процентной записи вначале задается положение рисунка по горизонтали, а затем, через пробел, положение по вертикали. Отношение между используемыми ключевыми словами и процентной записью следующее.

  • top left = left top = 0% 0% (в левом верхнем углу)
  • top = top center = center top = 50% 0% (по центру вверху)
  • right top = top right = 100% 0% (в правом верхнем углу)
  • left = left center = center left = 0% 50% (по левому краю и по центру)
  • center = center center = 50% 50% (по центру)
  • right = right center = center right = 100% 50% (по правому краю и по центру)
  • bottom left = left bottom = 0% 100% (в левом нижнем углу)
  • bottom = bottom center = center bottom = 50% 100% (по центру внизу)
  • bottom right = right bottom = 100% 100% (в правом нижнем углу)
Читайте также:  Таблица

В скобках указано, где располагается фоновый рисунок относительно контейнера.

При inherit значение наследуется у родителя элемента.

XHTML 1.0 CSS2.1 IE Cr Op Sa Fx

       

.

HTML5 CSS3 IE Cr Op Sa Fx

Объектная модель

[window.]document.getElementById(» elementID «).style.backgroundPosition

Браузеры

Internet Explorer до версии 7.0 включительно не поддерживает значение inherit .

CSS по теме

Источник

CSS background-position Property

The background-position property sets the starting position of a background image.

Tip: By default, a background-image is placed at the top-left corner of an element, and repeated both vertically and horizontally.

Default value: 0% 0%
Inherited: no
Animatable: yes. Read about animatable Try it
Version: CSS1
JavaScript syntax: object.style.backgroundPosition=»center» Try it

Browser Support

The numbers in the table specify the first browser version that fully supports the property.

CSS Syntax

Property Values

Value Description Demo
left top
left center
left bottom
right top
right center
right bottom
center top
center center
center bottom
If you only specify one keyword, the other value will be «center» Demo ❯
x% y% The first value is the horizontal position and the second value is the vertical. The top left corner is 0% 0%. The right bottom corner is 100% 100%. If you only specify one value, the other value will be 50%. Default value is: 0% 0% Demo ❯
xpos ypos The first value is the horizontal position and the second value is the vertical. The top left corner is 0 0. Units can be pixels (0px 0px) or any other CSS units. If you only specify one value, the other value will be 50%. You can mix % and positions Demo ❯
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

More Examples

Example

How to position a background-image to be centered at top:

body <
background-image: url(‘w3css.gif’);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center top;
>

Example

How to position a background-image to be bottom right:

body <
background-image: url(‘w3css.gif’);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: bottom right;
>

Example

How to position a background-image using percent:

body <
background-image: url(‘w3css.gif’);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 50% 50%;
>

Example

How to position a background-image using pixels:

body <
background-image: url(‘w3css.gif’);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 50px 150px;
>

Example

Use different background properties to create a «hero» image:

.hero-image <
background-image: url(«photographer.jpg»); /* The image used */
background-color: #cccccc; /* Used if the image is unavailable */
height: 500px; /* You must set a specified height */
background-position: center; /* Center the image */
background-repeat: no-repeat; /* Do not repeat the image */
background-size: cover; /* Resize the background image to cover the entire container */
>

Источник

background-position

Задает начальное положение фонового изображения, установленного с помощью свойства background-image . В CSS3 допустимо указывать несколько значений для каждого фона, перечисляя значения через запятую.

Синтаксис

background-position: [left | center | right | | ] || [top | center | bottom | | ] | inherit

= [left | center | right | | ] || [top | center | bottom | | ] | inherit.

Значения

У свойства background-position два значения, положение по горизонтали (может быть — left , center , right ) и вертикали (может быть — top , center , bottom ). Кроме использования ключевых слов положение также можно задавать в процентах, пикселах или других единицах. Если применяются ключевые слова, то порядок их следования не имеет значения, при процентной записи вначале задается положение рисунка по горизонтали, а затем, через пробел, положение по вертикали. Отношение между используемыми ключевыми словами и процентной записью следующее.

  • top left = left top = 0% 0% (в левом верхнем углу)
  • top = top center = center top = 50% 0% (по центру вверху)
  • right top = top right = 100% 0% (в правом верхнем углу)
  • left = left center = center left = 0% 50% (по левому краю и по центру)
  • center = center center = 50% 50% (по центру)
  • right = right center = center right = 100% 50% (по правому краю и по центру)
  • bottom left = left bottom = 0% 100% (в левом нижнем углу)
  • bottom = bottom center = center bottom = 50% 100% (по центру внизу)
  • bottom right = right bottom = 100% 100% (в правом нижнем углу)

В скобках указано, где располагается фоновый рисунок относительно контейнера.

При inherit значение наследуется у родителя элемента.

XHTML 1.0 CSS2.1 IE Cr Op Sa Fx

       

.

HTML5 CSS3 IE Cr Op Sa Fx

Объектная модель

[window.]document.getElementById(» elementID «).style.backgroundPosition

Браузеры

Internet Explorer до версии 7.0 включительно не поддерживает значение inherit .

CSS по теме

Источник

How to Center Background Images in CSS

By default, on a web page, an image appears on the top left corner of the screen and is repeated horizontally and vertically. However, to change its current position, CSS offers a “background-position” property that specifies the background image’s position, such as the center.

In this article, we will learn how to set the position of a background image with the help of examples. To do so, firstly, we will demonstrate the procedure of adding an image as a background in CSS.

Add Background Images Using “background-image” Property

For adding images in the background, the “background-image” property is utilized.

Following is the syntax to set a background image to an HTML element:

Here, “url()” specifies the image name or image folder path in which it exists.

Now, move to the practical example of using the background-image property.

Example: Inserting a Background Image Using CSS

In this example, we will create an element, and background will be added behind this element. You can add elements according to your choice and apply the background-image property to it:

After that, move to the CSS, use the “background-image” property, assign the image path or name in the as “url()” value of the background-image property:

background-image : url ( «img.jpg» ) ;

This will give the following outcome:

This is how you can add a background image in CSS.

How to Center Background Images Using “background-position” CSS Property?

The “background-position” property sets the background image’s position. The syntax will be as follows:

The image’s position can be specified as absolute, left, or right. More specifically, setting the “center” value will center the added background image.

Now, let us move to the practical example that demonstrates how to use the background-image and background-position properties in CSS.

Example: How to Set Background Image in Center?

We will set the background color and image path with the “background” property. Next, we will utilize the “background-position” property to set the background image in the center. Finally, we will set the “background-repeat” property to no-repeat for not repeating the image:

background : rgb ( 128 , 44 , 12 ) url ( «image.jpg» ) fixed ;

Once it is all done, execute the code, and let’s have a look at the final outcome:

Our background image is successfully positioned in the center of the page.

Conclusion

Background images can be added using the background-image property, whereas background position can be set using the background-position property. To the center, the background image in CSS sets the value of the background-position property to “center”. The article explains in detail how to add an image to the background using “background-image” and how to set its position using the “background-position” property.

About the author

Anees Asghar

I am a self-motivated IT professional having more than one year of industry experience in technical writing. I am passionate about writing on the topics related to web development.

Источник

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