- background-position
- Синтаксис
- Значения
- Объектная модель
- Браузеры
- CSS по теме
- CSS center position:absolute background
- 4 Answers 4
- How to center a background div?
- 1 Answer 1
- Solution 1 (jsfiddle)
- Solution 2 (jsfiddle)
- Solution 3 (jsfiddle)
- Solution 4 (jsfiddle)
- CSS background-position Property
- Browser Support
- CSS Syntax
- Property Values
- More Examples
- Example
- Example
- Example
- Example
- Example
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 center position:absolute background
I’m trying to keep the «sp» and «bg» divs centered at all times but I can’t seem to do it. It is centered up until the width of the window exceeds the width of the image. After that, the image stays to the left of the page. All I want to change is that the image should move to the center of the page at all widths. Ideal answer would be with keeping position: absolute. Thanks!
#slider-wrapper #slider #slider .bg #slider .sp
Any reason you couldn’t use background-image and use background-position to center and background-size: cover to keep it full width?
Some of your HTML is invalid.
As @ShayR mentioned below in his answer, apply the margin-left and margin-right auto to your slider-wrapper css. That should center that container on the screen left and right regardless of the screen size. As far as the img with 100% width and height, unless you don’t care about the aspect ration of the images, you should use the 100% only in one direction (width or height). You would probably want to use pre-sized images for best results.
You might want to use the text-align center and vertical-align as well in the css for the slider-wrapper to position your slider div at it’s center as well. That’s as far as I want to comment, considering that it will ultimately be affected by javascript.
4 Answers 4
Using this, the image width would always be 100% of the screen, which is not desired. When the window width exceeds the image width, I simply want the image to be in the center of the window, without being as wide as the window. Right now, all of the desired points already exist, except the fact that when the window width exceeds the image width, the image stays on the left side of the page, and doesn’t move to the center. Hope that makes sense. Thanks!
If you want to centre an element from css, you could use the margin clause:
As for the background, if you want a background for the element, you could also use the above code for it, and define the height property as well.
First of all, Clean up the CSS and get rid of the absolute positioning it becomes a real pain later in development.
Clean up HTML remove the containers why do you have these? You dont need to restate 100% if its in the CSS. Also the issue with %’s is they need a reference like 1000px to know what to scale relatively to.
CSS #slider-wrapper < clear:both; position: relative; max-width: 1000px; width: 100%; >#slider < position: relative; width:100% height:100% >.sp, .bg
This doesn’t work since it makes the images have the width of the screen at all times. As I mentioned in an earlier comment: Using this, the image width would always be 100% of the screen, which is not desired. When the window width exceeds the image width, I simply want the image to be in the center of the window, without being as wide as the window. Right now, all of the desired points already exist, except the fact that when the window width exceeds the image width, the image stays on the left side of the page, and doesn’t move to the center. Hope that makes sense. Thanks!
How to center a background div?
But problem: the scroll bar appears for the background block.
codepen.io/anon/pen/wBZqxa now in tht example ( thanks to @Shikkediel ) do you want the scroll for the horizontal axis?
If I understand it correctly, centering page body ‘oldskool’ as well should help. codepen.io/anon/pen/qEwXGQ
1 Answer 1
Here are a few ideas I could think of, with their issues. However, I could not reproduce the «blurry in IE» issue, so I don’t know which solution have it or not.
I did put «Extra markup» as an issue for solutions including a div ( #backgroundBlock ) only used to display the background image, as it is not semantic.
Solution 1 (jsfiddle)
- Description : Your first solution
- Issues :
- Extra markup
- On Chrome, depending on the page size, pixels can be aligned differently. You can see it on jsfiddle near the right border :
Solution 2 (jsfiddle)
- Not compatible with old browsers (IE8, FF3.5, . ; source)
- On Chrome, same alignment problem as in solution 1
Solution 3 (jsfiddle)
- Extra markup
- You have to use overflow-x: hidden on body to avoid horizontal scrollbar
- Not compatible with old browsers (IE8, FF3, . ; source). You should also use prefixes for compatibility ( -webkit- , -moz- , . ). I did not add them to keep the example simple
Solution 4 (jsfiddle)
- Description : Use of translate and ::before . Alternative version of solution 3. Pseudo-elements compatibility are not an issue here since every browser supporting 2D-tranforms supports ::before (source).
#backgroundBlock < position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden; >#backgroundBlock:before
- Extra markup
- Not compatible with old browsers (IE8, FF3, . ; source). You should also use prefixes for compatibility ( -webkit- , -moz- , . ). I did not add them to keep the example simple
There are other possibilities but I think most of them would have one of the above issues.
For example, you could set the #pageBody width to 2560px, set the background on it, add padding to have a content size of 820px and translate it in order to have it centered on the page (and prevent horizontal scrollbars using overflow-x on body ). This would be possible because the background image and page body both have fixed width.
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 */
>