NH

Rotating a background image with CSS

October 13, 2020

Problem

Background images can’t be rotated independently of the element using CSS. Rotating and element rotates the entire element, not just the background

.container-with-bg {
	background: no-repeat left center / auto 48px url("https://acpocketnews.com/wp-content/uploads/2020/04/Tom-Nook.jpg");
	height: 48px;
	padding: 0 0 0 48px;
	transform: rotate(5deg);
	width: 300px;
}
<div class="container-with-bg">
	Tom Nook
</div>

Solution

Add a pseudo element with the desired background and rotate the pseudo element

.container {
	height: 48px;
	width: 300px;
}

.container::before {
	background: no-repeat left center / auto 48px url(""https://acpocketnews.com/wp-content/uploads/2020/04/Tommy.jpg"");
	content: '';
	display: inline-block;
	height: 100%;
	transform: rotate(5deg);
	width: 48px;
}
<div class="container">
	Tommy
</div>

Reference


Hey, I'm Nancy Huynh
I'm a self-taught front-end developer relaxing in Toronto
This is a collection of new things I'm learning