position absolute gives parent no height

2019-06-14 15:28发布

问题:

I have two divs in a parent div. They render side by side

<image><info>

but on smaller screens I want them to render one under the other and swap positions, like

<info>
<image>

So, their real order in html is

<info>
<image>

and they both have float:right so they appear swapped and side by side. On smaller screens they both have float:none and thet appear one under the other as they should. I used Shlomi's answer from here and it works fine.

The problem.

When horizontal, I wan to align the divs on the left, but due to the float:right, they align right.

So I thought I give the container position:relative and the children position:absolute , so then I can do left:0; and right:0. This make the container have zero height and a vertical scrollbar appears. If I remove the position:absolute its back to normal, but no left aligned.

So either I can use position:absolute and fix container's height or my solution is stupid and maybe you suggest something else.

My code right now

#container{
   width: 100%;
   height: auto;
   display: block;
   margin-top: 30px ;  
   padding-bottom: 38px;
   clear: both;
   overflow: auto;
   position: relative;
}

#image{
    display: block;
    height: 221px;
    width : auto;
    float: right; 
    margin-right: 20px;
    position: absolute;
    clear: both;
    overflow: auto;
}

#info{
    width:-moz-calc(100% - 331px);width: -webkit-calc(100% - 331px);width: calc(90% - 331px);    
    height: 500px;
    display: block;
    float: right;
    position: absolute;
    clear: both;
    overflow: auto;
}

回答1:

You might use

float: left;

instead :)

Here is the fiddle of Shlomi updated :

https://jsfiddle.net/sk99xqdd/4/

I'm not sure if it answers your question ...