Html CSS:如何使 div 块*不*占用其父容器中的空间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9909194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 23:23:04  来源:igfitidea点击:

CSS: How to make a div block *not* take space in its parent container

csshtmlpositioningcss-position

提问by David Parks

If I have 2 div tags:

如果我有 2 个 div 标签:

<div id="parentDiv">
   <div id="childDiv"><!-- other html --></div>
   <!-- parent div html -->
</div>

I want the content of <div id="childDiv">to overlap the content <!-- parent div html -->.

我希望内容<div id="childDiv">与内容重叠<!-- parent div html -->

Reason (in case this looks like bad code design to anyone): I need a hack workaround in google sites, I cannot add custom code on the sidebar nav, only in the main html space, I want to float a div that takes no space and relatively position it over the side bar to get around the forced limitation.

原因(如果这对任何人来说看起来都是糟糕的代码设计):我需要在 google 站点中使用 hack 解决方法,我无法在侧边栏导航上添加自定义代码,只能在主 html 空间中,我想浮动一个不占用空间的 div并将其相对放置在侧杆上方以绕过强制限制。

I can do everything except stop the childDivfrom taking up space in it's bastardized main-page container.

我可以做任何事情,除了阻止childDiv它占用它的混蛋主页容器中的空间。

回答by S.Visser

You can give it a position absolute, and navigate it with margins.

你可以给它一个绝对位置,并用边距导航它。

    #childDiv {
      position: absolute;
      margin-top: -100px;
      margin-left: -100px;
    }

回答by Mr Lister

How about a simple

一个简单的怎么样

#childDiv {height:0; overflow:visible;}

#childDiv {height:0; overflow:visible;}

But you probably want it to have a background colour, hm? Hm.

但是您可能希望它具有背景颜色,嗯?嗯。

回答by Matthew Darnell

#parentDiv {
    position: relative;
}
#childDiv {
    position:absolute;
    top:0;
    left:0;
    width:100%;
}

If you need to bump the content around, or overlap stuff that is 'outside' of the sidebar, you can use negative margins to increase the width of the childDiv or move it up (to cover padding or margins you can't override).

如果您需要在侧边栏“外部”增加内容或重叠内容,您可以使用负边距来增加 childDiv 的宽度或将其向上移动(以覆盖无法覆盖的填充或边距)。

If you need to make the #childDiv cover the entire #parentDiv, you can use a bit of JavaScript to set a min-height on childDiv, then add a colored background or something to cover any content.

如果你需要让#childDiv 覆盖整个#parentDiv,你可以使用一些JavaScript 来设置childDiv 的最小高度,然后添加一个彩色背景或其他东西来覆盖任何内容。

var parentHeight = jQuery('#parentDiv').height();
jQuery('#childDiv').css('min-height',parentHeight + 'px');

回答by Frank van Wijk

You have to take the childblock out of the flow. The best way to do this is position: absoluteon the child divand position: relativeon the parent div.

您必须将子块从流中取出。最好的方法是position: absolute在 childdivposition: relativeparent上做到这一点div