Nesh
Nesh

Reputation: 2541

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/

Upvotes: 1

Views: 101

Answers (2)

Pranesh Ravi
Pranesh Ravi

Reputation: 19113

This should help.. You need to change the top and left also

https://jsfiddle.net/pranesh_ravi/zdvcm1mp/1/

Upvotes: 1

Mohammad Usman
Mohammad Usman

Reputation: 39322

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>	

Upvotes: 1

Related Questions