CSS变换比例,不要缩放子元素

时间:2014-11-20 23:32:21

标签: css css3 transform

如果我有一个包含少量子元素的div,那么它就是css变换缩放。我有一个我不想扩展的子元素

#parent{
    -webkit-transform: scale(.5);
}
 
span:last-child{
    -webkit-transform: Something to ignore the parent scale;
}
<div id="parent">
    <span>Child 1</span>
    <span>Child 2</span>
    <span>Child 3 (Don't Scale Me)</span>
</div>

这只能用css完成吗?不改变html或使用js。

4 个答案:

答案 0 :(得分:8)

不幸的是,这是不可能的。

你大致还有两个选择:

  1. 缩放所有其他元素,不包括您不想缩放的元素(但这不会缩放容器)。
  2. 缩放容器并重新缩放您不想缩放的元素(但这可能会使其看起来模糊)。
  3. 示例:

    // Example 1.
    span:not(:last-child) {
        display: inline-block; /* You can't scale inline elements */
        transform: scale(2);
    }
    
    // Example 2.
    #parent{
        transform: scale(.5);
    }
    
    span:last-child{
        transform: scale(2);
    }
    

答案 1 :(得分:3)

所有浏览器解决方案的输出都是纯净的(不模糊),但是对html的改动很小

另一种可能的解决方案是使用更干净的输出,但是对html代码进行少量更改,就是将元素放置在必须缩放的父元素之外。

之后,将子div设置为相对。现在,将最大值设置为0减去父级的高度,然后将其设置为0。

这样,子元素将不会受到影响并且不会变得模糊。

对我来说,此解决方案始终有效。

看看这个类似的问题,但是用更少的代码来简化示例:Scale parent element but remove scaling on child elements

#parent {
  height: 200px; width: 300px;
  background: beige;
  transition: transform 0.3s linear;
  transform-origin: top left;
}

#child {
  /* top value 0 is minus the height of parent*/
  top: -200px; left: 0px;
  position: relative;
  pointer-events: none;
}

.scale {
  transition: transform 0.3s linear;
  transform-origin: top left;
}

#parent:hover {
  transform: scale(2.0);
  transition: transform 0.3s linear;
}

/* affect child elements by hover, too */
#parent:hover + #child > .scale {
  transform: scale(2.0);
  transition: transform 0.3s linear;
}

/* set span to block for transforming */
span {
  display: block;
  padding-bottom: 10px;
}
<div id="parent">
</div>

<div id="child">
  <span class="scale">Child 1</span>
  <span class="scale">Child 2</span>
  <span>Child 3 (Don't Scale Me)</span>
</div>

代码段注释

/ *将范围设置为用于变换的块* /

How can I use CSS3 transform on a span?

/ *也通过悬停影响子元素* /

How to affect other elements when a div is hovered或更好的What does the “+” (plus sign) CSS selector mean?

结论

我认为没有其他解决方案可以得到干净的输出,因为缩放总是会影响子元素,但是您可以执行此解决方法。

这也应该在div的固定位置上起作用。

无论如何,您都必须更改html代码以获取干净的输出。

答案 2 :(得分:2)

我担心您需要使用更详细的选择器,例如#parent > span:not(:last-child)Example

答案 3 :(得分:0)

我发现Chrome hack可以解决模糊问题。

#parent { transform: scale(5);}
#child  { transform: scale(0.2)  translate3d( 0, 0, 0);}
相关问题