Home > Mobile >  html float:left does not keep divs beside each other
html float:left does not keep divs beside each other

Time:10-12

I need help with an apparently simple problem: preventing the rightmost of several wide float-left divs from moving down to the next set of lines without my specifically making the body width large enough to prevent this from happening. There are several suggested solutions to this problem in various Internet posts, but none of them works for me. The following code shows the problem.

    <!DOCTYPE html>
<html>
<style>

body {
//  width:800%;
width:600%;
//  width:400%;
//  width:200%;
}


div {
  padding-left:800px;
  padding-right:800px;
  text-align:center;
  border: 1px solid red; 
  float:left;
}

</style>

<body>

  <div>Div 1<br>line 2</div>
  <div>Div 2<br>line 2</div>
  <div>Div 3<br>line 2</div>
  <div>Div 4<br>line 2</div>
  <div>Div 5<br>line 2</div>

</body>
</html>

If no body width is specified, the five divs stack top to bottom, ignoring the float: left specification. But if a body width of 800px is specified, all five divs float properly. if a body width of 600px is specified, four divs float properly but one goes down to the next available space. And so on

I’m looking for code — presumably short – that will properly float all five divs side-by-side automatically, without my having to specify a body width of 800.

Help with this puzzle would be most appreciated.

Thanks

CodePudding user response:

You can try this inline-block approach instead of floats. Your broader use case might not work great with it though. I used span instead of body, but you can use body if you don't mind the white-space:nowrap on your entire body.

With inline-blocks though you have to do this stupid </div><div> thing to prevent spaces between your inline blocks. https://css-tricks.com/fighting-the-space-between-inline-block-elements/ talks about it.

span {
  display: block;
  white-space: nowrap;
}

div {
  padding-left: 800px;
  padding-right: 800px;
  text-align: center;
  border: 1px solid red;
  display: inline-block;
}
<span>
  <div>
  Div 1<br>line 2</div><div>
  Div 2<br>line 2</div><div>
  Div 3<br>line 2</div><div>
  Div 4<br>line 2</div><div>
  Div 5<br>line 2</div>
</span>

CodePudding user response:

You can put the 5 divs you have currently into 1 div, as shown

<div class="container">
    <div>Div 1<br>line 2</div>
    <div>Div 2<br>line 2</div>
    <div>Div 3<br>line 2</div>
    <div>Div 4<br>line 2</div>
    <div>Div 5<br>line 2</div>
</div>

The parent div should have a class or id so we can allign the other divs next to each other. Your css should look something like this,

<style>

.container {
  width: 100%;
  display: flex;
}

.container div {
  padding-left:800px;
  padding-right:800px;
  text-align:center;
  border: 1px solid red; 
  float:left;
}

</style>
  •  Tags:  
  • html
  • Related