Поворот background image css

How to Apply CSS3 Transforms to Background Images

CSS transformations are great, but they don’t (yet?) apply to background images. This article presents a workaround for those times when you really do want to rotate a background image, or to keep a background image fixed while its container element is rotated.

This article was updated in 2020. For more advanced CSS knowledge, read our book, CSS Master, 2nd Edition.

Scaling, skewing, and rotating any element is possible with the CSS3 transform property. It’s supported in all modern browsers without vendor prefixes.

#myelement  transform: rotate(30deg); > 

Great stuff. However, this rotates the whole element — its content, border and background image. What if you only want to rotate the background image? Or what if you want the background to remain fixed while the content is rotated?

There’s no W3C CSS proposal for background-image transformations. It would be incredibly useful, so perhaps one will appear eventually, but that doesn’t help developers who want to use similar effects today.

One option would be to create a new background image from the original, say rotated by 45 degrees. This could be achieved using:

  1. a server-side image manipulation process
  2. a client-side canvas -based image handling code, or
  3. APIs provided by some image-hosting CDN services.

But all these require additional effort, processing, and costs.

Fortunately, there’s a CSS-based solution. In essence, it’s a hack which applies the background image to a ::before or ::after pseudo element rather than the parent container. The pseudo element can then be transformed independently of the content.

Transforming the Background Only

The container element can have any styles applied, but it must be set to position: relative , since our pseudo element will be positioned within it. You should also set overflow: hidden unless you’re happy for the background to spill out beyond the confines of the container.

#myelement  position: relative; overflow: hidden; > 

We can now create an absolutely positioned pseudo element with a transformed background. The z-index is set to -1 to ensure it appears below the container’s content:

#myelement::before  content: ""; position: absolute; width: 200%; height: 200%; top: -50%; left: -50%; z-index: -1; background: url(background.png) 0 0 repeat; transform: rotate(30deg); > 

Note that you may need to adjust the pseudo element’s width, height and position. For example, if you’re using a repeated image, a rotated area must be larger than its container to fully cover the background.

CSS3 transformation on background

Fixing the Background on a Transformed Element

All transforms on the parent container are applied to pseudo elements. Therefore, we need to undo that transformation. For example, if the container is rotated by 30 degrees, the background must be rotated -30 degrees to return to its original position:

#myelement  position: relative; overflow: hidden; transform: rotate(30deg); > #myelement::before  content: ""; position: absolute; width: 200%; height: 200%; top: -50%; left: -50%; z-index: -1; background: url(background.png) 0 0 repeat; transform: rotate(-30deg); > 

Again, you’ll need to adjust the size and position to ensure the background adequately covers the parent container.

Here are the relevant demos live on CodePen:

The effects work in all major browsers and Internet Explorer back to version 9. Older browsers are unlikely to show transformations but the background should still appear.

Share This Article

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he’s been advocating standards, accessibility, and best-practice HTML5 techniques. He’s created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He’s written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

Источник

Rotate Background Image

Example of Rotate Background Image

Applying background images is a frequent frontend requirement. But at times, we may need to rotate those images in the background without affecting the orientation of content in the foreground. In this article, we will observe how the ::before pseudo-element of CSS can help us achieve the rotation of a background image. We will walk through the step-by-step construction of the following codepen.

* < font-family: sans-serif; >#imageContainer < position: relative; width: calc(100vh - 20px); height: calc(100vh - 20px); top: 10px; left: calc(50% - 50vh + 10px); background: transparent; color: white; overflow: hidden; >#imageContainer::before < content: ""; position: absolute; width: 100%; height: 100%; background-image: url("https://unused-css.com/media/seagull.jpg"); background-size: 100% 100%; transform: rotate(45deg) scale(1.45); z-index: -1; >

The first step is to create an element and set its background to be transparent. We do not set a background image on this element directly because we will be using it’s ::before (child) pseudo-element to host the image. To ensure the image doesn’t outgrow the parent element in size, we will hide the overflow.

Let’s provide the ::before pseudo-element with the background image. Note that providing a content attribute, be it an empty string, is necessary for having the pseudo-element generated. We also give it a z-index of -1 so that it does not lay over the content of the foreground which otherwise would get hidden behind the image.

With the image in place, all that is left is to apply rotation on the pseudo-element.

When we rotate the pseudo-element, blank space will be introduced at the corners. To get rid of that, we scale up the pseudo-element. The exact value of upscaling will vary in your case. It will be dependent on the aspect ratio of the element and the angle of rotation. One could discover some complex mathematics formula for calculating the precise value but the easier way appears to try the hit & trial approach until the background fully covers the element. And if the aspect ratio of the element can change, additional testing and adjustment will be needed to ensure the same visual results on various screen sizes.

Note that the transformations were not applied to the image but to the element having that image set as its background.

Conclusion

Using ::before or ::after pseudo-selectors, we can apply background images (and more visual enhancements) to elements without manipulating their own properties.

UnusedCSS helps website owners remove their unused CSS every day. Sign Up to see how much you could remove.

You Might Also Be Interested In

Источник

Transform CSS3 к фоновым изображениям. Rotate вращение фона

С помощью transform свойства CSS3 возможно масштабирование, перекос и поворот любого элемента. Это свойство поддерживается во всех современных браузерах без префиксов. Если вам необходимо поддерживать браузер Blackberry и браузер UC для Android, вам нужно использовать -webkit-префикс, например:

Однако это вращает весь элемент и все его содержимое, границу и фоновое изображение, текст и т.д.. Что делать, если вы хотите только повернуть только фоновое изображение? Или что, если вы хотите, чтобы фон оставался фиксированным, когда элемент вращается? В настоящее время у W3C нет предложения для преобразования фонового изображения. Это было бы невероятно полезно, поэтому я подозреваю, что он появится в конечном итоге, но это не помогает разработчикам, которые хотят использовать подобные эффекты сегодня. К счастью, есть решение. По сути, это хак, который применяет фоновое изображение к элементу до или после псевдоэлемента, а не к родительскому контейнеру. Затем псевдоэлемент может быть преобразован независимо.

Transform только фона

Элемент контейнера может иметь любые применяемые стили, но он должен быть установлен position: relative так, поскольку наш псевдоэлемент будет размещен внутри него. Вы также должны установить, overflow: hidden если вы не удовлетворены тем, что фон вылился за пределы контейнера.

Теперь мы можем создать псевдоэлемент со свойством position: absolute с преобразованным фоном. Для z-index установлено значение -1, чтобы убедиться, что оно отображается под содержимым контейнера.

Обратите внимание, что вам может потребоваться отрегулировать ширину, высоту и положение псевдоэлемента. Например, если вы используете повторяющееся изображение, повернутая область должна быть больше, чем его контейнер, чтобы полностью покрыть фон:

Фиксированый фон на преобразованном элементе

Все преобразования в родительском контейнере применяются к псевдоэлементам. Поэтому нам нужно отменить это преобразование, например, если контейнер повернут на 30 градусов, фон должен быть повернут на 30 градусов, чтобы вернуться в фиксированное положение:

#myelement < position: relative; overflow: hidden; -webkit-transform: rotate(30deg); transform: rotate(30deg); >#myelement:before

Опять же, вам нужно будет отрегулировать размер и положение, чтобы обеспечить адекватное покрытие фона для родительского контейнера. Эффекты работают во всех основных браузерах, а в Edge и Internet Explorer — до версии 9. IE8 не будет показывать никаких преобразований, но фон все равно появляется. IE6 и 7 не поддерживают псевдоэлементы, поэтому фон исчезает.Однако для поддержки этих древних браузеров вы можете применить фоновое изображение к контейнеру, а затем установить его «none» с помощью расширенного селектора или условного CSS.

Источник

How to rotate the background image in the container?

I want to rotate the image which is placed in the button of scrollbar in Chrome. Now I have a CSS with this content:

::-webkit-scrollbar-button:vertical:decrement < background-image: url(images/arrowup.png); -webkit-transform: rotate(120deg); -moz-transform: rotate(120deg); background-repeat: no-repeat; background-position: center; background-color: #ECEEEF; border-color: #999; >

I’d like to do this as well. There’s an example of something like this happening on iCloud — see how the vault texture rotates dynamically: icloud.com

I guess that maybe you no longer need and answer but maybe someone else would be interested. Here is a link for a tutorial that shows how to do it : http://www.sitepoint.com/css3-transform-background-image/

Unfortunately all of the provided solutions do not work in scroll bars. I ended up creating 4 separate pictures.

8 Answers 8

FYI, containers rotate about their center point, in case you’re having trouble getting exactly the transformation you want.

Yeah, but this is not rotating the background. This is faking it with an approximation. If you actually need the background to be rotated this will not help.

Very easy method, you rotate one way, and the contents the other. Requires a square though

#element < background : url('someImage.jpg'); >#element:hover < transform: rotate(-30deg); >#element:hover >*

Update 2020, May:

Setting position: absolute and then transform: rotate(45deg) will provide a background:

 

Hello World!

Original Answer:

In my case, the image size is not so large that I cannot have a rotated copy of it. So, the image has been rotated with photoshop . An alternative to photoshop for rotating images is online tool too for rotating images. Once rotated, I’m working with the rotated-image in the background property.

.reverse < transform: rotate(180deg); >.rotate < animation-duration: .5s; animation-iteration-count: 1; animation-name: yoyo; animation-timing-function: linear; >@keyframes yoyo < from < transform: rotate( 0deg); >to < transform: rotate(360deg); >> 
$(buttonElement).click(function () < $(".arrow").toggleClass("reverse") return false >) $(buttonElement).hover(function () < $(".arrow").addClass("rotate") >, function() < $(".arrow").removeClass("rotate") >) 

PS: I’ve found this somewhere else but don’t remember the source

I was looking to do this also. I have a large tile (literally an image of a tile) image which I’d like to rotate by just roughly 15 degrees and have repeated. You can imagine the size of an image which would repeat seamlessly, rendering the ‘image editing program’ answer useless.

My solution was give the un-rotated (just one copy 🙂 tile image to psuedo :before element — oversize it — repeat it — set the container overflow to hidden — and rotate the generated :before element using css3 transforms. Bosh!

I tried all solutions but none helped, below is what was my problem and how I solved it:

Problem: we have an image for desktops with landscape orientation but To show the same image but rotated (portrait) for mobile screens.

How: I just rotated the actual image in my assets folder the way I wanted (portrait), and then just used media queries to call that image for my background for mobiles, and that’s it.

(this was the easiest and quick solution I did.)

Источник

Читайте также:  Python opencv image tracking
Оцените статью