Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fit div (width) around floating divs

I have now searched for hours and couldn't find a workable solution for my problem, so I have you can give me some advice.

What I want is a div that wraps around some floating divs inside. Wrapping the height is no problem to me, but the width doesn't wrap right if the browser is resized to a width, where the floating elements jump down.

Here some example code:

HTML:

<div class="wrapper">

    <div class="block1">
    </div>

    <div class="block2">
    </div>
</div>

CSS:

body {
    border: solid 1px green;
}

.wrapper {
    border: solid 1px red;
    display: table;
}

div {
    display: block; 
}

.block1 {
    float: left;
    width: 390px;
    height: 390px;
    background-color: blue;
}

.block2 {
    float: left;
     width: 390px;
    height: 390px;
    background-color: yellow;
}

So basically I want the wrapping div to always have the width that the divs inside need. By resizing the window and letting the right div jump under the left the wrapping div should now have the width of 390px for this example.

I need this solution for a responsive website I'm trying to make and I need it as soon as possible.

A pure CSS solution would be prefered, but JS or jquery would also do.

like image 848
Balfear Avatar asked Nov 12 '22 17:11

Balfear


1 Answers

You can use a CSS media query on the wrapper div. Like so:

@media (max-width: 783px) {
 .wrapper {
    max-width: 390px;
  }
}

See this codepen for an example:

like image 152
keithwyland Avatar answered Nov 17 '22 01:11

keithwyland