Parent height based on relative positioned children

妖精的绣舞 提交于 2019-12-11 03:45:01

问题


css is a marvelous thing except when you are blocked and you haven't had your ahaha moment.

Today I am having trouble to scale the height of my parent div containing a relative positioned element to the proper height. This is because the children is using a top property.

Now I know how top works on relative positioned element and I understand why it does not contains the proper height value.

What I want to know is:
"Is it possible to include this top property in the height of my parent without switching to paddings or margins ?"

Here is a fiddle of my code: http://cssdeck.com/labs/unfeydw0
Or a simple code below:

html:

<div>
    <div class="relative">
    </div>
</div>

css:

.relative {
    position: relative;
    top: 42px;
    height: 40px;
    width: 100%;
    background: red;
}

Thank you.


回答1:


When you specify "top" you will move your object always without affecting parent's height. Which means that if you want to affect it's height you will have to move it with margins.

So your answer is: "No it is not possible". Here is the specification: http://www.w3.org/TR/CSS2/visudet.html#Computing_heights_and_margins




回答2:


You could add an empty element after the .relative and set it's height to that of the .relative's top positioning.




回答3:


If you want to pass it with jquery

var positionToTop = $(".relative").css("top");
$(".relative").parent().css({"top":positionToTop});

i forked a CSSDeck here for you




回答4:


I found that what worked for me in a similar situation was instead of setting top: I set margin-top:. That will cause the parent div to resize itself appropriately.



来源:https://stackoverflow.com/questions/15136754/parent-height-based-on-relative-positioned-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!