首页 文章

内部相对的绝对位置没有定义的高度

提问于
浏览
1

我试图将一个绝对div放在一个相对定位的div中 . 但我不想为相对div定义高度 .

相对div具有背景颜色,当我在相对div之外时't define a height the absolute div goes ' . I can't control how many lines the text will be so the height of the divs change

HTML

<div class="row top-footer">
    <div class="top-footer-text text-center">
        <div class="test">
        <h1>title</h1>

        <div class="footer-btn-wrap">
          <div class="footer-btn"><a href="...">button</a></div>

          <div class="footer-btn"><a href="...">button</a></div>
        </div>
        </div>      
    </div>
</div><!-- /top-footer -->

CSS

.top-footer {
position: relative;
background-color: #686a6f;
width: 100%;
padding-top: 40px; margin: 0;
}

.test { 
position: absolute; 
top: 0px; margin: 0;
}

编辑

我想.top-footer(position:relative)包含.test(position:absolute),在.test的顶部和底部有空格/填充/边距 . div的高度未知,因为内容可能占用多行,具体取决于屏幕大小

4 回答

  • 1

    在子div周围添加空格是相当微不足道的 . 但是,防止父div崩溃是比较棘手的,是你需要首先解决的问题 . 你遇到的问题是,父母相对定位且孩子绝对定位,整个页面上唯一的元素实际上是孩子所在的地方......即便如此,它甚至可以为父母提供足够的空间 . 儿童! DOM的其余部分将表现得好像元素不得不在整个地方使用绝对定位......这可能会在以后的大脑调试布局问题上有点沉重 .

    我能想到的唯一可能的解决方案是:

    • 使用javaascript嗅出子div的高度并将其应用于父级 . 如果您使用像jQuery这样的库,但需要额外的下载文件,并且如果这是您正在使用它的唯一任务,则会使您的网站不必要地笨重,这是一项相当简单的工作 . 这也无法解决子div模糊页面上其他元素的问题 .

    • 在你的孩子身上使用 display:inline-block 重做你的CSS(并且可能需要进行大量的改造,具体取决于你有多远和样式的复杂性)...这会阻止父级崩溃,但可能会给你额外的布局的问题 .

    • 将CSS(同上)重写为 float:left 子div . 然后你需要使用CSS "clear hack"以防止父divv崩溃,虽然这是一小块你可以从其他地方剪切和粘贴的CSS ......一个简单的工作 .

    如果您决定使用这样的绝对定位,我首选的解决方案是使用jQuery(选项1),因为我的大多数工作都倾向于使用它的程度...这是一个我会方便的工具和代码执行这项任务将是非常微不足道的 .

    编辑 - 这是一个让你入门的小提琴 . https://jsfiddle.net/fo8mq1vf/

  • 0

    这就是代码输出的样子:https://jsfiddle.net/s3zLa54t/2/ . 父div( .top-footer )确实包含 .test div . 您使用什么浏览器查看输出?

    至于填充,我猜你没有看到改变 padding-top 的任何影响 . 尝试删除 .test div中的 top: 0px 属性 .

    如果这不是您想要的,请在此澄清问题 .

  • 0

    你的问题的答案就是删除

    position:absolute from your absolute div (.test)
    position:relative from your relative div (.top-footer)
    height:300px from your relative div (.top-footer)
    

    这是https://jsfiddle.net/s3zLa54t/3/的测试版本,主div下有多个div . 您可以检查它是否超出了灰色背景 .

  • 0
    .top-footer {
        position: absolute;
        background-color: #686a6f;
        width: 100%;
        padding:0px;
        margin: 0;
    }
    .test h1{ 
        padding-left:20px;
        position: relative; 
        top: 5px; margin: 0;
        float:left;
        color:#FFF;
    }
    .footer-btn,.footer-btn-wrap
    {
        padding-left:200px;
        color:#FFF;
    }
    .footer-btn a{
        padding:5px 10px;
        float:left;
        color:#ffffff;
        text-transform:capitalize;
        text-decoration:none;
    }
    

相关问题