How do I unskew background image in skewed layer (CSS)?

Zuno picture Zuno · Aug 17, 2013 · Viewed 14.4k times · Source

I'm trying to display a profile photo like this / - / (the slashes represent slants using skewX, the hyphen represents a horizontally-aligned background image).

The problem is that this code also skews the background image:

.photo {
transform: skewX(35deg); 
-ms-transform: skewX(35deg); /* IE 9 */
-webkit-transform: skewX(35deg); /* Safari and Chrome */
width: 100px; 
height: 92px; 
border-right: 1px solid black; 
border-left: 1px solid black; 
background-image: url('silhouette.png'); 
background-repeat: no-repeat; 
background-position: top left; 
}

...

<div class="photo"></div>

I've tried to reverse the background skew like this:

.photo {
transform: skewX(35deg); 
-ms-transform: skewX(35deg); /* IE 9 */
-webkit-transform: skewX(35deg); /* Safari and Chrome */
width: 100px; 
height: 92px; 
border-right: 1px solid black; 
border-left: 1px solid black; 
}

.photo div {
transform: skewX(-35deg); 
-ms-transform: skewX(-35deg); /* IE 9 */
-webkit-transform: skewX(-35deg); /* Safari and Chrome */
width: 100%; 
height: 100%; 
background-image: url('silhouette.png'); 
background-repeat: no-repeat; 
background-position: top left; 
}

...

<div class="photo"><div></div></div>

...but I get / [-] / (the background doesn't fit flush to the slants).

I've been at this all day, please can you help me? I've got coder's bock!

Answer

nirazul picture nirazul · Aug 17, 2013

I'd rather use a pseudo element that's holding the background-image. The key to the solution is using transform-origin:

Example

.photo {
    transform: skewX(35deg); 
    -ms-transform: skewX(35deg); /* IE 9 */
    -webkit-transform: skewX(35deg); /* Safari and Chrome */
    width: 100px; 
    height: 92px; 
    border-right: 1px solid black; 
    border-left: 1px solid black; 

    /* new styles */
    position: relative;
    overflow: hidden;
    -webkit-transform-origin: top left;
    -ms-transform-origin: top left;
    transform-origin: top left;
}

.photo::before {
    content: "";
    transform: skewX(-35deg); 
    -ms-transform: skewX(-35deg); /* IE 9 */
    -webkit-transform: skewX(-35deg); /* Safari and Chrome */
    background-image: url('http://placekitten.com/200/200'); 
    background-repeat: no-repeat; 
    background-position: top left; 

    /* new styles */
    position: absolute;
    -webkit-transform-origin: top left;
    -ms-transform-origin: top left;
    transform-origin: top left;
    width: 1000%; /* something ridiculously big */
    height: 1000%; /* something ridiculously big */
}