How to use skew only in the parent element?

别来无恙 提交于 2019-11-29 07:15:02

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);
}

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!).

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.

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.

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