Search code examples
htmlcssalignment

divs' horizontal alignment erratic in container div


I want to have 4 divs aligned horizontally in a parent div. The parent div has width:100%;

All child divs have width:20%; I want the remaining 20% to be empty space, distributed evenly between them (around 7% between every two divs).

I have tried this code:

<div id="header" style="position:absolute; width:90%; border:2px solid black;">
    <div id="h_left" style="left:0; border:1px dotted black; width:20%;"> Left side material </div>
    <div id="h_center1" style="margin:auto; border:1px dotted black; width:20%;"> Center 1 material </div>
    <div id="h_center2" style="margin:auto; border:1px dotted black; width:20%;"> Center 2 material </div>
    <div id="h_right" style="right:0; border:1px dotted black; width:20%;"> Right side material </div>
</div>

But this produces a very disappointing result: enter image description here

How can I improve my code so that all divs are aligned accordingly with equal space between them?


Solution

  • Divs are a display block by standard. This means that each one will be on its own line. I recommend doing a 1 hour free starter course on CSS that will help you with all these assumptions.

    You can do what you want to style this, there are many options. But I recommend flex box. Flex box and Grid will be your friends in CSS. Here is a simple guide I still reference.

        <div
          style="display: flex; justify-content: space-between; position:absolute; width:90%; border:2px solid black;"
        >
          <div id="h_left">Left side material</div>
          <div id="h_center1">Center 1 material</div>
          <div id="h_center2">Center 2 material</div>
          <div id="h_right">Right side material</div>
        </div>

    here is a CodeSandbox that shows it