首页 > 解决方案 > CSS 过渡 - 将子 div 扩展到其父宽度和高度

问题描述

这是我在起点方面所做的 - https://codepen.io/illianyh/pen/bGpJgma

/*For IE CSS3 transition property works starting IE10*/
* {box-sizing: border-box;}
body {font-family: 'Playfair Display', serif; margin: 0;text-align: center}
h1 {font-weight: normal;color: #6A5953}
kbd {font-size: 0.9em;display:inline-block;line-height:1.1;}

div, h2, img {
  -webkit-transition: .5s ease-in-out;
  -moz-transition: .5s ease-in-out;
  -o-transition: .5s ease-in-out;
  transition: .5s ease-in-out;
}
h2 {
  color: #E39F81;
  text-shadow: 1px 1px 0 #FFE3BD;
}
h2:hover {
  text-shadow: 1px 1px 0 #FFE3BD, 2px 2px 0 #FFE3BD, 3px 3px 0 #FFE3BD, 4px 4px 0 #FFE3BD, 5px 5px 0 #FFE3BD;
  
}

.parent {
  width: 560px;
  height: 386px;
  margin: 0 auto;
  background: black;
  position: relative;
}

.box {
  width: 50%; 
  position: absolute;
  right: 0;
  top: 153px;
}

.four {
  width: 423px;
  height: 248px;
  background-color: #95A1B1;
  margin: 0 auto;
}
.four:hover {
  width: 500px;
  height: 300px;
  box-shadow: 0 15px 15px -10px rgba(0,0,0, .5);
}
<h1>CSS3 Transition examples</h1>
<div class="parent"></div>
<div class="box"><div class="four"><kbd>width, height, box-shadow</kbd></div></div>

</div>

我如何让孩子向父母的内部和顶部扩展自己,而不是在外部扩展自己。

这是我想要实现的图表:

初始状态(箭头代表孩子展开的方向):

在此处输入图像描述

这是最终状态,最终子 div 具有与父级相同的宽度和高度。父级现在隐藏在子级后面: 在此处输入图像描述

标签: csscss-transitions

解决方案


  • 父级具有相对位置的固定大小
  • 孩子有百分比或任何尺寸类型,其位置绝对和左上角位置与父固定尺寸相关(甚至可以是百分比父)
  • 过渡适用于已知尺寸

这是我为您修复的示例:CODEPEN

.parent {
  position:relative;
  width: 560px;
  height: 386px;
  margin: 0 auto;
  background: black;
  position: relative;
  background: red;
}
.child {
  position:absolute;
  background: blue;
  height:70%;
  width: 50%;
  right: -20%;
  top:15%;
  box-shadow: 0 15px 15px -10px rgba(0,0,0, .5);
  transition: all 0.5s ease; 
}
.parent:hover .child{
  top: 0%;
  right: 0;
  width:100%;
  height:100%;
  box-shadow: 0 0px 0px 0px rgba(0,0,0, .5);
}
.text{
  position:absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

推荐阅读