- background-position
- Синтаксис
- Значения
- Объектная модель
- Браузеры
- CSS по теме
- background-position-x
- Try it
- Syntax
- Values
- Formal definition
- Formal syntax
- Examples
- Basic example
- HTML
- CSS
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- Relative position with background image
- Update: now the top margin works, but not the left one 🙁
- 3 Answers 3
- Set Background Image in CSS
- Use the background:url() to Set the Background Image in CSS
- Use the Relative Path /image/picture to Set the Background Image in CSS
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 по теме
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.
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.
Relative position with background image
I have a div I would like which I have placed at 25% from the top. However, the 25% are computed with respect to the size of the background image and not with respect to the size of the visible screen. How can this be fixed?
Update: now the top margin works, but not the left one 🙁
3 Answers 3
1) use absolute positioning:
2) make sure your div is not within another positioned element (if you’re not sure of this, just put it just inside the tag, nothing else)
on the dive that you want placed 25% from top of visible screen.
There’s no reason to have «div» before #myDiv — there should only be one element per page with the same ID, so — specifying what type of element it is is overkill (especially if the id has «Div» in it).
I agree. I do this out of habbit and would obviously not name the element myDiv. I just did this for demo purposes only.
if you use relative position then the percentage will be calculated from the parent element.
if you use absolute position the percentage will be calculated from the size of the screen.
So try to using position absolute instead of relative.
edited answer for comment, just add extra div with id wrapper and change postitions, see example below:
body < background: #eeeeee url('pix/bg-noether-2.jpg') no-repeat center top; background-attachment: fixed; overflow: hidden; text-align: center; >#wrapper < position:absolute; width:100%; height:100%; >#container bla bla bla
Set Background Image in CSS
- Use the background:url() to Set the Background Image in CSS
- Use the Relative Path /image/picture to Set the Background Image in CSS
- Use the Relative Path ../image/picture to Set the Background in CSS
This article introduces methods to set background images in CSS. We will discuss how to set the path of the image so that the background image correctly shows up. Furthermore, we will discuss the different relative paths.
Use the background:url() to Set the Background Image in CSS
We can use the background property to set the background image in CSS. The URL() function will hold the image’s file path as the background image. The background property is the shorthand of several other properties associated with the background. Those properties in order are background-color , background-image , background-repeat , background-attachement and background-position . Using the background property, we can assign the values for all these properties in a short way.
The criticl point where we can get wrong is while writing the path of the image in the URL() function. We should be aware of the location of the image, and the path that is written in the URL() function should be relative to the CSS file. If we write the CSS in the HTML file itself, the path should be relative to the HTML file.
In the example below, the image named picture is inside the image folder. The image folder and the following CSS file style.css is in the same folder. Therefore, the following code will set the background image.
The folder structure is shown below:
web ├── style.css ├── HTML │ └── test.html └── image └── picture
body background: url(image/picture); >
Use the Relative Path /image/picture to Set the Background Image in CSS
We can use the /image/picture file path format to set the background image in CSS. In such a format, the image is located inside the image folder. The image folder is located at the root of the current web.
In the example below, we have set the picture image as the background image. The location of the CSS file does not matter in this format. We do not need to write the file path relative to the CSS file. The file path is written relative to the root of the current web. It means that the image folder lies in the root directory.