CSS scale without overlapping

Viewed 824

I need to scale the middle div using transform scale(1.3). It works of course but the problem is that after scaling it overlaps neighbor divs. Is it possible to get rid of overlap using just CSS? This is how it is now looks like:

enter image description here

But I want it this way

enter image description here

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

3 Answers

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

Edited:

margin-rate fixed

transform property does not reflects to the element width or height. Maybe you can use zoom instead. The downside is that Firefox does not support it: https://caniuse.com/?search=zoom

You can add a margin to the scaled box to prevent the overlap.

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

In your preview, the divs are also aligned vertically which can't happen with a simple margin since they're inline. Use a flex in the main container to align them vertically.

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