Riggun
Riggun

Reputation: 315

CSS scale without overlapping

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>

Upvotes: 3

Views: 2179

Answers (3)

Osman Durdag
Osman Durdag

Reputation: 965

.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

Upvotes: 2

kashif197
kashif197

Reputation: 23

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

Upvotes: 1

JohnRambo
JohnRambo

Reputation: 518

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

Upvotes: 3

Related Questions