How to use skew only in the parent element?

二次信任 提交于 2020-01-10 03:03:04

问题


Is there any way to use skew only in a parent element? I need to create something like a 'diamond' as a mask and the child elements can't be affected. There is no way, in this case, to use png as a mask. Thanks in advance!


回答1:


It's really easy, you just need to unskew the thing for the children. Unskew means applying another skew transform, but of opposite angle this time.

.parent { transform: skewX(45deg); }
.parent > * { transform: skew(-45deg); }

In general, if you apply a number of transforms on a parent element and you want the child elements to go back to normal, then you have to apply the same transforms, only in reverse order (the order does matter in most cases!) and with a minus for angle/ length values used for skew, rotate or translate. In the case of scale, you need a scale factor of 1/scale_factor_for_parent. That is, for scale, you would do something like this:

.parent { transform: scale(4); }
.parent > * { transform: scale(.25); /* 1/4 = .25 */ }

A diamond shape with children is pretty easy.

DEMO

Result:

HTML:

<div class='wrapper'>
  <div class='diamond'>
    <div class='child'>Yogi Bear</div>
    <div class='child'>Boo Boo</div>
  </div>
</div>

CSS:

.wrapper {
  overflow: hidden;
  margin: 0 auto;
  width: 10em; height: 10em;
}
.diamond {
  box-sizing: border-box;
  margin: 0 auto;
  padding: 4em 1em 0;
  width: 86.6%; height: 100%;
  transform: translateY(-37.5%) rotate(30deg) skewY(30deg);
  background: lightblue;
}
.child {
  transform: skewY(-30deg) rotate(-30deg);
}



回答2:


Any transform property affects the element which is applied to and all of his children.

So the only way to skew a single "parent" element is to have it with no children (i.e.: it can't be also a parent!).




回答3:


Could ou try to elaborate a bit on what do you want to get as a result ?

skew(), like all transform properties always affects the child elements. You could try to use two HTML blocks at the same position, one with the skew() and the other with the contents.

Also, if you just want a diamond, a rectangular box with scale() and rotate() should be enough, but again with no children.

And if you want that diamond as a mask, I'm pretty sure it would be easier to render the parts NOT present in the diamond. Rendering the outside parts of the diamond should not be that hard, after all, they're only rectangle triangles.




回答4:


the only way to achieve this is to take the child element out of the document flow using position:absolute; and putting an equal negative degree skew on the child.

The problem with this is that you will now have to resize your parent manually.



来源:https://stackoverflow.com/questions/13027357/how-to-use-skew-only-in-the-parent-element

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