Css transform rotate background

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.

Источник

How to Rotate Container Background Image using CSS?

CSS, or Cascading Style Sheets, is a powerful tool for web designers to control the visual presentation of a website. One of the most common visual effects used in web design is the ability to rotate a Container Background. Rotating a container background image is a simple and effective way to add a dynamic touch to the website design. By using CSS, we can achieve this effect easily and without the need for any additional software or tools.

Syntax

Following is the syntax to rotate container background image using CSS −

Here «angle» is the amount of rotation to apply to the element, specified in degrees.

Rotating container background image using CSS

Here, we will discuss the simple steps to rotate a container background image using CSS.

Step 1: Create the HTML container

The first step in rotating a container background image is to create the HTML container. We can use any HTML element for doing this, such as a div, section, or article. In the below example, we will use a div element.

The above code creates a container with the class name «container».

Step 2: Add the background image using CSS

In this step, we will add the background image to the container using CSS. We can use the «background-image» property to do this. For example −

The above code will add a background image to the container using the URL of the image

Step 3: Rotate the container background image using CSS

The final step is to rotate the container background image using CSS. For example &minnus;

The above code will rotate the container background image by 30 degrees using the «transform» property.

Now, we will discuss how to rotate a container background image CSS, including the different methods and properties.

Example 1

Here is an example to rotate a container background image by 30 degrees using transform property.

The transform property allows us to apply various transformations to the HTML element, including rotation. To rotate an element, we use the «rotate()» function, which takes an angle value in degrees as its parameter. The below example code will rotate the container by 30 degrees.

      

To rotate an image by 30 degrees using transform property

Before Rotation

Example Image



After Rotation

Example 2

Here is an example to rotate a container background image by 45 degrees using transform-origin property.

The transform-origin property allows us to specify a point around which the element should be rotated. The below example code will rotate the container by 45 degrees around its bottom-left corner.

      

Rotating Container Background Image

To rotate an image by 45 degrees using transform-origin Property

Example 3

Here is an example to rotate a container background image by 30 degrees using transition property.

The «transition» property allows us to specify the duration and timing function of a CSS property, including the «transform» property. The below example code will rotate the container background image by 30 degrees with a smooth animation when the user hovers over it.

   body < text-align: center; >.container < width:350px; height:150px; border:2px solid; margin:auto; background-image: url(/html/images/test.png); background-repeat: no-repeat; transition: transform 0.5s ease; >.container:hover 

Rotating Container Background Image

The Image will rotate by 45 degrees when the mouse hovers over it

Conclusion

The rotating a container background image using CSS is an easy and effective way to make the website more engaging. With just a few lines of code, we can add a dynamic touch to the design that will make the website stand out.

Источник

Как применить трансформацию 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 с помощью современных селекторов или через условные комментарии.

Источник

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.

Источник

Читайте также:  Disable a href Link using CSS
Оцените статью