【问题标题】:CSS scale without overlappingCSS 缩放不重叠
【发布时间】:2020-09-16 23:01:40
【问题描述】:

我需要使用 transform scale(1.3) 来缩放中间的 div。它当然可以,但问题是缩放后它会与相邻的 div 重叠。是否可以仅使用 CSS 来消除重叠? 这就是它现在的样子:

但我想要这样

.main {
  width: 100%;
  height: 500px;
  background-color: gray;
  padding: 100px;
}

.box {
  width: 100px;
  height: 100px;
  background-color: red;
  margin: 2px;
  display: inline-block;
  border: 2px;
  border-style: solid;
  border-color: black;
}

.scaled-box {
  width: 100px;
  height: 100px;
  -webkit-transform: scale(1.3);
  -moz-transform: scale(1.3);
  transform: scale(1.3);
  display: inline-block;
  background-color: green;
  opacity: 0.7;
}
<div class="main">
  <div class="box"></div>
  <div class="scaled-box"></div>
  <div class="box"></div>
</div>

【问题讨论】:

标签: html css


【解决方案1】:

.main {
    width: 100%;
    height: 500px;
    background-color: gray;
    padding: 100px;
    --scale-rate:1.5; /* You can change scale from this line */
}

.box {
    width: 100px;
    height: 100px;
    background-color: red;
    display: inline-block;
    border: 2px;
    border-style: solid;
    border-color: black;
}

.box:first-child{
  margin-right: calc(((100px * var(--scale-rate)) - 100px) / 2); /* 100px is scaled-box width*/
}

.box:last-child{
  margin-left: calc(((100px * var(--scale-rate)) - 100px) / 2); /* 100px is scaled-box width*/
}

.scaled-box {
    width: 100px;
    height: 100px;
    -webkit-transform: scale(var(--scale-rate));
    -moz-transform: scale(var(--scale-rate));
    transform: scale(var(--scale-rate));
    display: inline-block;
    background-color: green;
    opacity: 0.7;
}
<div class="main">
    <div class="box"></div>
    <div class="scaled-box"></div>
    <div class="box"></div>
</div>

已编辑:

保证金率固定

【讨论】:

    【解决方案2】:

    transform 属性不反映到元素 widthheight。也许您可以改用zoom。缺点是 Firefox 不支持:https://caniuse.com/?search=zoom

    【讨论】:

      【解决方案3】:

      您可以为缩放框添加边距以防止重叠。

      .scaled-box {
      margin: 20px;
      width: 100px;
      height: 100px;
      -webkit-transform: scale(1.3);
      -moz-transform: scale(1.3);
      transform: scale(1.3);
      display: inline-block;
      background-color: green;
      opacity: 0.7;
      }
      

      在您的预览中,div 也是垂直对齐的,这不能通过简单的边距发生,因为它们是内联的。在主容器中使用 flex 将它们垂直对齐。

      .main {
      display: flex;
      align-items: center;
      width: 100%;
      height: 500px;
      background-color: gray;
      padding: 100px;
      }
      

      【讨论】:

        猜你喜欢
        • 2014-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-07
        • 2012-06-27
        • 2021-07-21
        相关资源
        最近更新 更多