Css повернуть задний фон

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.

Читайте также:  Smtp server java mail

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

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

Читайте также:  Сверточная нейронная сеть python код

Пожалуйста, посмотрите демонстрационную страницу для примера. Полный код хранится внутри 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.

Читайте также:  Maven узнать версию java

Источник

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

Источник

Оцените статью