首页 > 解决方案 > 移动后如何使文本出现在居中图像旁边?

问题描述

基本上,我有一个我想在页面中间居中的块。这个块在技术上应该有图像和文本。当块没有悬停时,我只希望图像显示在页面的中心。当块悬停时,我希望图像向左移动一点,并让文本出现在它的右侧。到目前为止,我已经设法使图像居中,使其在悬停时向左移动,并让悬停显示文本。问题是,文字在图像下方。我理解这是因为图像和文本位于不同的 div 中,所以它会出现在之后是有道理的。但是,我不确定如何将它们放在同一个 div 中,并确保当块没有悬停时图像在页面上处于死点。这可能吗?

具体来说,到目前为止,这是该部分的 HTML 代码:

<section class="about-us">
    <!-- Image division -->
    <div class="chatBox">
        <img src='./art/chatboxAbout.png' width= "150" height = "150" />
    </div>
    <!-- Text division, the actual about-us part -->
    <div class="about-us-text-container">
        <!-- Header part -->
        <h1>about us</h1>
        <!-- Horizontal line for styling -->
        <hr />
        <!-- Actual text -->
        <p>For artists, not by artists</p>
    </div>
</section>

和CSS:

/* General sizing and format for the about-us segment */
.about-us{
    width: 100%;
    height: 200vh;
    background-color: #fff;
}

/* Formatting for the chatBox image, basic stuff */
.about-us .chatBox{
  position: relative;
  margin-top: 50px;
  text-align: center;
  transition: transform 0.3s ease; /* Preparing for transition */
  transition: translateX(0px); /* What the transition is */
}

/* Move left on hover effect */
.chatBox:hover{
  transform: translateX(-200px);
}

/* Formatting for the general text div */
.about-us .about-us-text-container{
  margin-top: 50px;
  text-align:center;
  margin-left: 15px;
  opacity: 0; /* Don't display unless hovered */
  transform: 1s; /* Setting duration for the hover opacity transition */
}

/* Show on hover effect */
.chatBox:hover + .about-us-text-container{
  opacity: 1;
}

/* Formatting for the header */
.about-us .about-us-text-container h1{

}

/* Formatting for the horizontal line */
.about-us .about-us-text-container hr{

}

/* Formatting for the paragraph */
.about-us .about-us-text-container p{

}

到目前为止,这是整个代码的 JSFiddle 链接:https ://jsfiddle.net/bypvm6fu/

任何帮助表示赞赏!太感谢了!

标签: cssflexboxhovercss-transitionscentering

解决方案


这是一个可能的解决方案。我在您的代码中进行了很多更改,主要内容是:容器仅包含您已经拥有的元素(而不是200vh= 窗口高度的两倍)。只需在其周围添加另一个容器,并在其后添加兄弟姐妹。transition影响all, 即width,opacity和在transform: scale不悬停时保持图像居中。并且hover是在容器上,而不是在图像上,这样可以防止您之前的跳跃效果:

.about-us {
  width: 100%;
  height: 150px;
  background-color: #fff;
  display: flex;
  justify-content: center;
  align-content: center;
  margin-top: 50px;
}

.about-us .chatBox {
  position: relative;
  text-align: center;
}

.about-us .about-us-text-container {
  text-align: center;
  margin-left: 15px;
  opacity: 0;
  transition: all 1s;
  width: 0;
  transform: scale(0);
}

.about-us:hover .about-us-text-container {
  opacity: 1;
  width: 150px;
  transform: scale(1);
}
<section class="about-us">
  <div class="chatBox">
    <img src="https://picsum.photos/150" width="150" height="150" />
  </div>
  <div class="about-us-text-container">
    <h1>about us</h1>
    <hr />
    <p>For artists, not by artists</p>
  </div>
</section>


推荐阅读