Wizardre Wizardre - 7 months ago 11
HTML Question

CSS Help Floating a div to center when enough space

I'm trying to center a div in the web browser when there is enough space. If not it should be collapsed between 2 divs.

This is the collapsed view

enter image description here

And this would be the expanded view
enter image description here

I've tried so many different things but nothing seems to work right. When I get something that looks right, the

filterDiv
ends up going over the top of
titleDiv
or
buttonDiv
or both.

Here's some code that I started with and should represent the collapsed view when the browser isn't very wide.

<style type="text/css">
.controlsDiv{
background-color:yellow;
border: 1px solid black;
}
.titleDiv{
background-color:Red;
width:25em;
height: 5em;
border: 1px solid black;
}
.filterDiv {
background-color: gainsboro;
width: 600px;
height: 10em;
border: 1px solid black;
}
.buttonDiv{
width:25em;
height:5em;
background-color:green;
border: 1px solid black;
}

</style>

<div class="controlsDiv" >
<div class="titleDiv">
<h2>titleDiv</h2>
</div>
<div class="filterDiv">
<h2>filterDiv</h2>
<h2>Centered in Browser Window</h2>
<h2>titleDiv and ButtonDiv Collapsed</h2>
</div>
<div style:clear:both></div>
<div class="buttonDiv">
<h2>buttonDiv</h2>
</div>
</div>


Thank you in advance!

Answer

You can always position absolute required div:

<style type="text/css">
    .controlsDiv{
        background-color:yellow;
        border: 1px solid black;
    }
    .titleDiv{
        background-color:Red;
        width:25em;
        height: 5em;
        border: 1px solid black;
    }
    .filterDiv {
        background-color: gainsboro;
        width: 600px;
        height: 10em;
        border: 1px solid black;
    }
    @media(min-width: 900px) {
        .filterDiv {
        position: absolute;
        left: calc(50% - 300px);
        top: 0;
     }
    }
    .buttonDiv{
        width:25em;
        height:5em;
        background-color:green;
        border: 1px solid black;
    }
</style>