Home > database >  force float:left on divs without "white-space:nowrap"
force float:left on divs without "white-space:nowrap"

Time:01-06

have something like this:

<div >

    <div >
      
      <img src="image" alt="">
      
      <p>
          text...
      </p>
      
    </div>
    
    <div >
      
      <img src="image" alt="">
      
      <p>
          text...
      </p>

    </div>
    
</div>

I would like the "floating" divs to float on the left side of each other even though they are overflowing their container.

I tried just using "float:left" on the floating divs, but it doesn't work. They stack on each other.

So, I have found a workaround using "display:inline-block" on the floating elements and "white-space:nowrap" on the container and it works but it doesn't help in my case.

.container{
    width:600px; 
    border:2px solid black;
    overflow:hidden;
    display:block;
    white-space:nowrap; /* delete this and see the actual floating divs layout*/
}

.floating{
    width:66%;
    display: inline-block;
}

img{
  width:120px; 
  height:120px;
  float:left;
}

Indeed, the "white-space:nowrap" prevents my texts to wrap around the imgs in my floating divs, which is the initial intent. The "white-space:nowrap" does what it should do so this trick only seems to work when one doesn't care about wrapping the content inside the div. But I do in this case.

So, all in all, if I keep the white-space property, my 2 divs float as they should but the content inside them is messed up. And if I don't use the property, the content inside the divs is preserved but the divs don't float.

https://jsfiddle.net/8n0um9kz/

Is there any solution that gets me what I want ?

Thanks.

PS: I used a width of 66% for both the floating divs in the example just so that you could see both at once for illustration. In my case they are 100% each of course.

CodePudding user response:

yes. you have a solution.

Instead of using 'white-space : no-wrap' on the container you can use 'display : flex' and 'flex-wrap : wrap ' on the container to allow the items to the next line when they come end of the container. further use 'justify-content : flex -start'

CodePudding user response:

I got it like this.

.container{
    width:600px; 
    display:flex;  //required
    align-items: flex-start; //optional
    overflow:hidden;
}

.floating{
    min-width: 66%; //required
}

img{
  width:120px; 
  height:120px;
  float:left;
}

The key aspect was to use 'min-width' instead of 'width' and 'display:flex' on the container.

No need to use block display, remove float, justify content or wrap/unwrap anything.

'align-items: flex-start' is only required if the floating divs should keep their respective height, otherwise they will take the height of the tallest div. Which isn't a problem, unless you use background colors for your floating divs that are different from the container's.

https://jsfiddle.net/b83rzL07/1/

Thanks.

  • Related