background-position

background-position-x

The background-position-x CSS property sets the initial horizontal position for each background image. The position is relative to the position layer set by background-origin .

Try it

The value of this property is overridden by any declaration of the background or background-position shorthand properties applied to the element after it.

Syntax

/* Keyword values */ background-position-x: left; background-position-x: center; background-position-x: right; /* values */ background-position-x: 25%; /* values */ background-position-x: 0px; background-position-x: 1cm; background-position-x: 8em; /* Side-relative values */ background-position-x: right 3px; background-position-x: left 25%; /* Multiple values */ background-position-x: 0px, center; /* Global values */ background-position-x: inherit; background-position-x: initial; background-position-x: revert; background-position-x: revert-layer; background-position-x: unset; 

The background-position-x property is specified as one or more values, separated by commas.

Values

Aligns the left edge of the background image with the left edge of the background position layer.

Aligns the center of the background image with the center of the background position layer.

Читайте также:  Javascript nan is false

Aligns the right edge of the background image with the right edge of the background position layer.

The offset of the given background image’s left vertical edge from the background position layer’s left vertical edge. (Some browsers allow assigning the right edge for offset).

The offset of the given background image’s horizontal position relative to the container. A value of 0% means that the left edge of the background image is aligned with the left edge of the container, and a value of 100% means that the right edge of the background image is aligned with the right edge of the container, thus a value of 50% horizontally centers the background image.

Formal definition

Initial value 0%
Applies to all elements
Inherited no
Percentages refer to width of background positioning area minus width of background image
Computed value A list, each item consisting of: an offset given as a combination of an absolute length and a percentage, plus an origin keyword
Animation type a repeatable list of

Formal syntax

background-position-x =
[ center | [ [ left | right | x-start | x-end ]? ? ]! ]#

=
|

Examples

Basic example

The following example shows a simple background image implementation, with background-position-x and background-position-y used to define the image’s horizontal and vertical positions separately.

HTML

CSS

div  width: 300px; height: 300px; background-color: skyblue; background-image: url(https://mdn.dev/archives/media/attachments/2020/07/29/17350/3b4892b7e820122ac6dd7678891d4507/firefox.png); background-repeat: no-repeat; background-position-x: center; background-position-y: bottom 10px; > 

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-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 */
>

Источник

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.

Источник

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 по теме

Источник

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