Nesh Nesh - 2 months ago 7
CSS Question

Expand child div in a container keeping the center same - CSS

Following is my HTML/CSS code which is working fine the only thing I am unable to make is that keeping center of child div fixed while increasing the size of the child div inside a container. Let me know how could I achieve this effect.

HTML

<div class="container">
<div class="rect"></div>
</div>


CSS

.container {
width: 400px;
border: 1px solid #CECECE;
margin: auto;
height: 400px;
position: relative;
}
.rect {
border: 1px solid red;
width: 100px;
height: 100px;
margin: auto;
left: 150px;
top: 150px;
position: absolute;
transition: width 2s, height 2s, border 2s;
}
.rect:hover {
border: 1px solid green;
width: 200px;
height: 200px;
}


Fiddle - https://jsfiddle.net/zdvcm1mp/

Answer

Use CSS3 transform property and scale element on hover instead of changing width and height.

.container {
  width: 400px;
  border: 1px solid #CECECE;
  margin: auto;
  height: 400px;
  position: relative;
}
.rect {
  border: 1px solid red;
  width: 100px;
  height: 100px;
  margin: auto;
  left: 150px;
  top: 150px;
  position: absolute;
  transition: transform 2s, border 2s;
  transform-origin: center;
}
.rect:hover {
  border-color: green;
  transform: scale(2);
}
<div class="container">
  <div class="rect"></div>
</div>