Home  >  Q&A  >  body text

How to achieve horizontal positioning of three divs in HTML?

<p>I'm creating a sample website with three horizontal partitions. I want the leftmost partition to be 25% wide, the middle partition to be 50% wide, and the right partition to be 25% wide so that the partitions fill 100% of the space horizontally. </p> <pre class="brush:php;toolbar:false;"><html> <title> Website title </title> <div id="the whole thing" style="height:100%; width:100%" > <div id="leftThing" style="position: relative; width:25%; background-color:blue;"> left menu </div> <div id="content" style="position: relative; width:50%; background-color:green;"> random content </div> <div id="rightThing" style="position: relative; width:25%; background-color:yellow;"> right menu </div> </div> </html></pre> <p>https://i.stack.imgur.com/NZDJe.jpg</p> <p>When I execute this code, the divs appear overlapping. I want them to appear side by side! </p> <p>What should I do? </p>
P粉419164700P粉419164700425 days ago522

reply all(2)I'll reply

  • P粉478445671

    P粉4784456712023-08-22 13:51:31

    I know this is a very old question. I'm posting a solution to this problem here, using FlexBox. Here is the solution:

    #container {
      height: 100%;
      width: 100%;
      display: flex;
    }
    #leftThing {
      width: 25%;
      background-color: blue;
    }
    #content {
      width: 50%;
      background-color: green;
    }
    #rightThing {
      width: 25%;
      background-color: yellow;
    }
    <div id="container">
    
      <div id="leftThing">
        左侧菜单
      </div>
    
      <div id="content">
        随机内容
      </div>
    
      <div id="rightThing">
        右侧菜单
      </div>
    
    </div>

    Just add display:flex to the container! No need to use floats.

    reply
    0
  • P粉842215006

    P粉8422150062023-08-22 11:58:42

    I recommend not using floats to handle this situation, I prefer to use inline-block.

    A few more points to consider:

    • Inline styles are bad for maintainability
    • There should be no spaces in the selector name
    • You have ignored some important HTML tags, such as <head> and <body>
    • You did not include doctype

    Here is a better way to format the document:

    <!DOCTYPE html>
    <html>
    <head>
    <title>网站标题</title>
    <style type="text/css">
    * {margin: 0; padding: 0;}
    #container {height: 100%; width:100%; font-size: 0;}
    #left, #middle, #right {display: inline-block; *display: inline; zoom: 1; vertical-align: top; font-size: 12px;}
    #left {width: 25%; background: blue;}
    #middle {width: 50%; background: green;}
    #right {width: 25%; background: yellow;}
    </style>
    </head>
    <body>
    <div id="container">
        <div id="left">左侧菜单</div>
        <div id="middle">随机内容</div>
        <div id="right">右侧菜单</div>
    </div>
    </body>
    </html>

    There is also a jsFiddle for reference.

    reply
    0
  • Cancelreply