【问题标题】:div does not resize to height if child is positioned absolutly如果孩子绝对定位,div 不会调整到高度
【发布时间】:2017-04-30 09:41:04
【问题描述】:

我在 DIV 中有一个图像。 我想将图像“悬垂”在 DIV 之外一点,所以我将其定位为绝对,父容器定位为相对。当我这样做时,父 DIV 不再调整其高度以包含图像。 我该怎么做?

HTML

      <div class=".twelve.columns" id="header">
        <div id="logoWrapper">
                <img src="https://nbson.com/sni/images/logo.png" class="ssImg">
                <div class="clr"></div>
        </div>      
      </div>  

CSS

.ssImg{
    width:100%;
}
.clr{
    clear:both;
}
#header{
     margin-top:0;
     background:#000;    
     position:relative;
     width:100%;
     border:1pt solid pink; 
}

JSFiddle

【问题讨论】:

  • 如果你想在一个元素上放置两个类,使用&lt;div class="twelve columns"&gt;,而不是&lt;div class=".twelve.columns"&gt;

标签: html css


【解决方案1】:

绝对定位元素完全从文档流中移除,因此它们的尺寸不能改变其父元素的尺寸。 如果你真的必须在保持子元素为 position: absolute 的同时实现这种效果,你可以使用 JavaScript [...]

要在没有 javascript 的情况下获得所描述的效果,您可以对底部或顶部使用负值。我还为您的具体示例更新了您的JSFiddle

.ssImg{
	width:100%;
}
.clr{
	clear:both;
}
#header{
	 margin-top:0;
	 background:#000;	 
	 position:relative;a
	 width:100%;
	 border:1pt solid pink;	
}

#logoWrapper{
	width:15%;
	min-width:120px;
	margin-left:10px;
	position:relative; /* this is new */
        bottom: -40px; /* this is new */
}
<div class="twelve columns" id="header">
    <div id="logoWrapper">
            <img src="https://nbson.com/sni/images/logo.png" class="ssImg">
            <div class="clr"></div>
    </div>      
</div>

【讨论】:

    【解决方案2】:

    这个怎么样?

    html, body {   
      height: 100%;
      padding: 20px;
    }
    
    .ssImg{
       width: 100%;
    }
    
    #header{
      background-color: #000;	 
      position: relative;
      width: 100%;
      height: 100%; /* Set the height what you want */
      border: 1pt solid pink;	
    }
    
    #logoWrapper{
      width: 15%;
      min-width: 120px;
      position: absolute;
      top: -15px;
      left: -25px;
    }
    <div id="header">
      <div id="logoWrapper">
        <img src="https://nbson.com/sni/images/logo.png" class="ssImg">
      </div>      
    </div>

    【讨论】:

      【解决方案3】:

      首先:

      如果您想在一个元素上放置两个类,请使用 &lt;div class="twelve columns"&gt;,而不是 &lt;div class=".twelve.columns"&gt;

      其次,关于你的问题:

      绝对定位的元素会从流程中移除,因此在计算父元素的尺寸时不再考虑。

      您可以通过在元素上显式设置您需要的heightwidth 来解决它。

      【讨论】:

        猜你喜欢
        • 2017-07-03
        • 1970-01-01
        • 1970-01-01
        • 2011-07-18
        • 1970-01-01
        • 2012-01-01
        • 2012-07-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多