首页 > 解决方案 > 在灵活高度的内容框上悬停设置宽度

问题描述

我在一个灵活的内容框上创建了一个悬停效果,它改变了内框的宽度以显示里面的文本。我需要这个框的高度灵活,以便可以添加更多内容,但是,我不希望在悬停时改变高度。

我已经在下面链接了到目前为止我得到的东西,左边的框显示了我想要的静态高度效果,右边的框显示了当我添加更多文本时会发生什么,这会导致我悬停时高度变化的问题通过将文本包装在其中。

https://jsfiddle.net/ndpty6xa/

.flex {
  display: flex;
  justify-content: center;
}

.box {
  width: 50%;
  background-color: red;
  border: 2px solid black;
  min-width: 200px;
  flex-direction: column;
  margin: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.content {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: white;
  width: 0%;
  height: 90%;
  transition: all .5s;
}

.text {
  position: relative;
  text-align: center;
  overflow: hidden;
}

.box:hover>.content {
  width: 90%;
}

@media(max-width: 450px) {
  .flex {
    flex-wrap: wrap;
  }
  .box {
    flex-grow: 1;
  }
}
<div class=flex>

  <div class=box>
    <div class=content>
      <div class=text>
        <h3>This</h3>
        <p>Works</p>
      </div>
    </div>
  </div>

  <div class=box>
    <div class=content>
      <div class=text>
        <h3>This doesnt</h3>
        <p>TestTe stTestTestTest TestTestTestT estTestT estTes tTestTe stTestTestTest</p>
      </div>
    </div>
  </div>

</div>

我不认为我很擅长解释这一点,但希望有人明白这一点。

标签: htmlcssflexbox

解决方案


您可以有不同的想法,而不是为宽度设置动画,而是在其上方设置一个叠加层以模拟相同的效果:

.flex {
  display: flex;
  justify-content: center;
}

.box {
  width: 50%;
  background-color: red;
  border: 2px solid black;
  min-width: 200px;
  flex-direction: column;
  margin: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.content {
  position: relative;
  display: flex;
  flex-direction:column;
  justify-content: center;
  align-items: center;
  text-align: center;
  background-color: white;
  width: 90%;
  height: 90%;
}
.content:before {
  content:"";
  position:absolute;
  top:0;
  left:50%;
  right:0;
  bottom:0;
  background:red;
  z-index:1;
  transition: all .5s;
}
.content:after {
  content:"";
  position:absolute;
  top:0;
  right:50%;
  left:0;
  bottom:0;
  background:red;
  z-index:1;
  transition: all .5s;
}

.box:hover>.content:before {
  left: 100%;
}
.box:hover>.content:after {
  right: 100%;
}

@media(max-width: 450px) {
  .flex {
    flex-wrap: wrap;
  }
  .box {
    flex-grow: 1;
  }
}
<div class="flex">

  <div class="box">
    <div class="content">
        <h3>This</h3>
        <p>Works</p>
    </div>
  </div>

  <div class="box">
    <div class="content">
        <h3>This also works!</h3>
        <p>TestTe stTestTestTest TestTestTestT estTestT estTes tTestTe stTestTestTest</p>
    </div>
  </div>

</div>


推荐阅读