微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使 div 高度或位置适应其内容的相对位置

如何解决如何使 div 高度或位置适应其内容的相对位置

所以我试图找到这个问题的答案,但我不能。也许我只是措辞不当。

这是我的情况。我有一个使用行和列响应式制作的网站。

在我的一列中,我希望它包含的图像稍微偏移一点,以便在其上方的列上重叠。

这是它的样子(请注意,每列都添加了红色边框以使其更加明显):

enter image description here

所以我的问题是这个。每当我使用 {position: relative; top: -20%;},它会在图像下方创建一个我不知道如何删除的空白区域(以蓝色突出显示)。

代码有许多不同的 CSS 文件,所以我只需要链接 HTML 部分和 CSS 摘要,以避免不必要地使这变得复杂。

.resize {
  height: 80%;
}

#is1-img-1 {
  height: auto;
  max-width: 100%;
  position: relative;
  top: -20%;
}
<section id="index-section-1" class="large-padding">
  <!-- Left: image,Right: text -->
  <div class="row">
    <!-- Row 1/2 -->
    <div class="col-s-12 col-l-6 resize">
      <!-- Row content: image -->
      <img id="is1-img-1">
    </div>
    <div class="col-s-12 col-l-6">
      <!-- Row content: text -->
      <img class="line">
      <!-- For line svg - separator -->
      <h2>Enjoyable place for all the family</h2>
      <p>Our relaxed surroundings make dining with us a great experience for everyone. We can even arrange a tour of the farm before your meal.</p>
    </div>
  </div>
  <div class="row flip-on-mobile">
    <!-- Row 1/2 -->
    <div class="col-s-12 col-l-6">
      <!-- Row content: text -->
      <img class="line">
      <!-- For line svg - separator -->
      <h2>The most locally sourced food</h2>
      <p>All our ingredients come directly from our farm or local fishery. So you can be sure that you’re eating the freshest,most sustainable food.</p>
    </div>
    <div class="col-s-12 col-l-6">
      <!-- Row content: image -->
      <img id="is1-img-2">
    </div>
  </div>
</section>

我假设,如果我将 div 的内容移开 20%,那么使 div 本身达到高度的 80% 应该可以,但是当我这样做时,它会完全覆盖 {position: relative;顶部:-20%}。它只是再次将图像放入 div 中。

解决方法

添加一个完整的答案。

该问题的解决方案可以是使用 20% 的负边距:

{
  margin-top: -20%;
}

关于原始 CSS:由于 position: relative 的工作方式,它会在图像底部生成额外的空白。元素仍然使用原始空间来影响布局,当使用 top/left/right/bottom 值移动它时,它只会移动视觉,但不会改变计算的布局。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?