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

混江龙づ霸主 提交于 2019-11-29 12:30:57

问题


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!


回答1:


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 */
}


来源:https://stackoverflow.com/questions/18289643/how-do-i-unskew-background-image-in-skewed-layer-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!