Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solid background behind a rotated image in pure CSS

Tags:

html

css

Is there a way i can draw the black "background" behind the image using pure CSS ?

I am persuaded that it can be done using the :before pseudo-class. But i can't make it work. I have also tried using shadows, but the final result is not similar what i am trying to achieve.

Scope and requirements:

Modern browsers, no javascript, no jQuery, no plugins and no extra HTML markup.

Before answering:

I know there are zillion ways to achieve what i am trying to do, however i am really looking forward for a pure CSS solution. As stated before, trying to avoid extra markup and javascript for something as simple as that. Thanks!

image

Here is a fiddle and the code below.

img {
  position: absolute;
  top: 100px;
  left: 100px;
  -webkit-transform-origin: center left;
  -moz-transform-origin: center left;
  -ms-transform-origin: center left;
  -o-transform-origin: center left;
  transform-origin: center left;
  -webkit-transform: rotate(-2deg);
  -moz-transform: rotate(-2deg);
  -ms-transform: rotate(-2deg);
  -o-transform: rotate(-2deg);
  transform: rotate(-2deg);
}
img:before {
  background: #000;
  -webkit-transform-origin: center left;
  -moz-transform-origin: center left;
  -ms-transform-origin: center left;
  -o-transform-origin: center left;
  transform-origin: center left;
  -webkit-transform: rotate(-4deg);
  -moz-transform: rotate(-4deg);
  -ms-transform: rotate(-4deg);
  -o-transform: rotate(-4deg);
  transform: rotate(-4deg);
  width: 300px;
  height: 300px;
  content: ".";
}
<!doctype html>
<html>

<body>
  <img width="300" height="150" src="http://upload.wikimedia.org/wikipedia/en/7/70/Example.png" />
</body>

</html>
like image 721
Pierre Avatar asked Mar 03 '26 18:03

Pierre


2 Answers

It seems like the before: element is ignored on img tags - http://jsfiddle.net/GVdYe/

Added a div (sorry :-)

like image 88
ptriek Avatar answered Mar 05 '26 12:03

ptriek


The problem you're having is related to how pseudo-elements work.

Before and after elements are rendered inside their parent. So:

 div:before{ content:'before'; } 
 div:after{ content:'after'; } 

renders basically like this:

<div> <span>before</span> Hello <span>after</span> </div>

You can't put other elements in img, because img is a replaced element, and therefore can't apply pseudo-elements to it. Read the spec.

So, the easiest option would be to wrap the image in an <a> (as images sometimes are) and apply your before style to the a.

Alternatively, accept the non-rotated shadow box-shadow provides.

CSS has limitations unfortunately, so you're going to have to compromise somewhere, either in design (I would argue this is the way to go) or in markup.

like image 31
bookcasey Avatar answered Mar 05 '26 12:03

bookcasey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!