【问题标题】:Why is there space between my 2 divs even though I made them overlap?即使我让它们重叠,为什么我的 2 个 div 之间还有空间?
【发布时间】:2021-12-17 03:42:14
【问题描述】:

文本的顶部应该与图像的顶部一致,但事实并非如此。为什么? 我让这两个 div 重叠。它们之间的唯一区别是宽度(一个设置为 50%,另一个设置为 100%),但是当涉及到这个问题时,改变宽度并不会改变任何事情。我将文本 div 设为 50%,因为我希望文本不与图像上的植物接触。 The circled area of this image isn't supposed to be empty

It's even worse on small screens. The text here overlaps the footer (It shouldnt)

.intro-img-div{
    position: relative;
    height: 300px;
    width: 100%;
    overflow: hidden;
    align-content: center;
    margin:auto;
    display: flex;
    justify-content: center;
    align-items: center;

}
.menu-intro-img{

    position: relative;
    width: 100%;
}
.menu-intro-text{
    position: absolute;
    top: 0;
    right: 0;
    z-index: 2;
    vertical-align: middle;
    max-width: 50%;

    height: 300px;
    margin-bottom: 30px;
    margin: 20px;
    padding: 20px;
    text-align: center;
}
.menu-intro-h1{
    font-size: 3em;
}
.menu-intro-text p{
    font-size: 1.5em;
}
<main>
      <h1 class="text-centered">Our Menu</h1>
    <div class="menu">
      <div class="menu-intro">  

          <div class="intro-img-div">
              <img src="style/img/menuintroimg.jpeg" alt="Background image of our food" class="menu-intro-img">
          </div>

              <div class="menu-intro-text">
                  <h1 class="menu-intro-h1">A look at <span class="red-text">Jacque's</span>

                  </h1>
                  <p>Scroll down and see what we have to offer!</p>
              </div>


      </div>
    </div>

</main>

【问题讨论】:

    标签: html css responsive-design frontend


    【解决方案1】:

    如果.menu-intro-text 不应该有任何周围的空格,为什么它同时有marginpadding

    .menu-intro-text{
        position: absolute;
        top: 0;
        right: 0;
        height: 300px;
    
        vertical-align: middle;   /* <--- remove */
    
        margin-bottom: 30px;      /* <--- remove */ 
        margin: 20px;             /* <--- remove */
        padding: 20px;            /* <--- remove */
    }
    

    在我看来,如果您希望两个项目重叠,那么给其中一个赋予另一个没有的边距和填充是没有意义的。

    您还应该删除vertical-align: middle,因为当底部有剩余空间时,这会固有地在顶部创建空白。

    此处的文字与页脚重叠(不应该)

    由于额外的边距,您的图像比您计划的 300 像素高度更高,总共 340 像素(300 像素 + 20 像素上边距 + 20 像素下边距),但您可能看不到下边距。

    此外,即使在您忽略边距时的 300 像素中,由于您设置的填充,还有 40 像素(顶部 20 像素,底部 20 像素)的进一步“浪费”,尽管(再次)您可能看不到底部填充。

    【讨论】:

    • 更不用说margin-bottom 已经被margin 覆盖了。 h1 也有默认浏览器边距
    • @MaxiGui:这不是特殊性吗?还是纯粹是marginmargin-bottom的排列顺序?实际上,我不确定。我不倾向于混合它们。
    • margin-bottom 是因为人们订购它的方式。但基于不推荐的代码中有一对h1 的事实。我猜他是初学者
    • 即使我删除了边距和填充,仍然有一些空间
    • 你设置vertical-align: middle; 所以它总是空格
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2022-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-28
    相关资源
    最近更新 更多