2017-06-01 78 views
1

这是一个常见的问题,但我仍然没有找到任何解决方案,我的问题。绝对定位的孩子和父母的高度是0

.parent是一个滑块,.child是图像。 我需要通过.child高度(这是一个绝对定位元素)到.parent

.parent0px高度。有任何想法吗?

在此先感谢。

<div class="parent"> 
    <img class="child"></div> 
</div> 

.child { 
    position: absolute; //It must be absolute , because slider works with this 
    width: 100%; 
    top: 0; 
    left: 0; 
    right: 0; 
} 
+0

你知道的图像尺寸或宽高比? –

+0

你可不可以添加另一个''这是'相对'但没有'可见度'?这将使隐藏的图像占用空间。 – Chris

+0

Javascript。但在滑块上设置高度并让孩子相应地适应......而不是相反。 –

回答

1

正如我在评论中提到的,你也许可以添加 <img>元素。一个与position: absolute - 作为您的应用程序需要,另一个与visibility: hiddenposition: relative

如果您不想混淆标记,则可以使用伪元素执行类似操作,例如:after:before。但这个想法是一样的。

父母现在占据了图像的全部高度。这个解决方案可能会也可能不会工作,这取决于您的应用程序,这在您的问题中不太清楚,但也许值得一试。

.parent { 
 
    background: #AAA; 
 
} 
 

 
.child { 
 
    position: absolute; 
 
} 
 

 
.child-hidden { 
 
    visibility: hidden; 
 
}
<div class="parent"> 
 
    <img class="child" src="http://www.extremekitcars.com/wp-content/uploads/2016/01/Sports-Cars.png"> 
 
    <img class="child-hidden" src="http://www.extremekitcars.com/wp-content/uploads/2016/01/Sports-Cars.png"> 
 
</div>

+1

它工作:)我已经做了一些修改,在我的情况下,完成。谢谢你们,你救了我的一天! –

+0

很高兴能帮到你!您是否希望ne发布替代解决方案?这是一个更漂亮.. – Chris

2

自从你知道图像的尺寸,则可以由宽度除以高度并获得纵横比。然后将其作为垂直填充百分比应用于父级,这将使父级响应地匹配图像大小。

.child { 
 
    position: absolute; 
 
    width: 100%; 
 
    top: 0; 
 
    left: 0; 
 
    right: 0; 
 
} 
 

 
.parent { 
 
    border: 1px solid red; 
 
    position: relative; 
 
    padding-bottom: 39.86451277%; /* (765/1919) * 100 */ 
 
}
<div>some content</div> 
 

 
<div class="parent"> 
 
    <img class="child" src="http://via.placeholder.com/1919x765"> 
 
</div> 
 

 
<div>more content</div>

+1

相当漂亮的解决方案,如果尺寸是已知的。 – Chris

+0

已同意@Chris。 –

相关问题