Поворот фонового изображения 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.)

Источник

Как применить трансформацию CSS3 к фоновым картинкам

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

Хорошая штука. Однако вращается элемент целиком — его содержимое, границы и фоновая картинка. Что делать, если вы желаете повернуть только фоновое изображение? Или чтобы фон остался на месте, а элемент поворачивался?

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

К счастью, есть решение. В сущности, это хак, который добавляет фоновое изображение к псевдоэлементу :before или :after , а не к родительскому контейнеру. Псевдоэлемент может трансформироваться независимо.

Трансформация только фона

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

Теперь мы можем создать абсолютно позиционированный псевдоэлемент с трансформируемым фоном. Свойство z-index задаём как -1, это гарантирует что фон появится под содержимым контейнера.

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

Фиксация фона у трансформируемых элементов

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

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

Опять же, необходимо настроить размер и положение чтобы фон адекватно вписывался в родительский контейнер.

Пожалуйста, посмотрите демонстрационную страницу для примера. Полный код хранится внутри HTML.

Эффект работает в IE9, Firefox, Chrome, Safari и Opera. IE8 не покажет никаких трансформаций, но фон появится.

IE6 и 7 не поддерживает псевдоэлементы, поэтому фон исчезнет. Однако, если вы хотите поддерживать эти браузеры, можно добавить фоновое изображение к контейнеру, а затем установить его как none с помощью современных селекторов или через условные комментарии.

Источник

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. See how much you could save on your website:

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.

Источник

Читайте также:  Is php good or bad
Оцените статью