2016-10-06 23 views
1

以下是我的HTML/CSS代碼工作正常,我無法做的唯一的事情是保持中心的子div固定,同時增加子div的大小在一個容器內。讓我知道我怎麼能達到這個效果。展開容器中的子div保持中心相同 - CSS

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

小提琴 - https://jsfiddle.net/zdvcm1mp/

回答

1

使用CSS3 transform財產和懸停scale元素而不是改變widthheight

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

+0

我注意到,使用'scale'也增加了邊框的寬度2倍,我怎樣才能讓這個保持相同的邊框寬度 – Nesh

+1

@Nesh在這種情況下,你可以按照Pranesh的建議改變'top'和'left'的位置,因爲'scal e'會改變一個元素的所有特徵。 –