Max Bündchen
Max Bündchen

Reputation: 1394

CSS divs don't align correctly

That's a simplified code where I have one absolute div with four relatives divs inside as four columns. Why the inside divs don't align with the top of the external div?

P.S.: I know there's other ways to make that but the real code is more complex and that's the kind of solution I need.

<div style="position: absolute; top: 100px; left: 100px; width: 800px; height: 400px; background-color: red; margin: 0; padding: 0;">
  <div style="position: relative; display: inline-block; height: 100%; width: 25%; background-color: blue;">
    <p>1</p>
    <p>2</p>
    <p>3</p>
    <p>4</p>
  </div><div style="position: relative; display: inline-block; height: 100%; width: 25%; background-color: yellow;">
    <p>1</p>
    <p>2</p>
  </div><div style="position: relative; display: inline-block; height: 100%; width: 25%; background-color: green;">
    <p>1</p>
    <p>2</p>
    <p>3</p>
    <p>4</p>
    <p>5</p>
  </div><div style="position: relative; display: inline-block; height: 100%; width: 25%; background-color: pink;">
    <p>1</p>
    <p>2</p>
  </div>
</div>

Upvotes: 1

Views: 484

Answers (1)

j08691
j08691

Reputation: 208032

Because inline elements have their vertical alignment set to baseline by default. Change it to top:

div > div {
    vertical-align:top;
}
<div style="position: absolute; top: 100px; left: 100px; width: 800px; height: 400px; background-color: red; margin: 0; padding: 0;">
    <div style="position: relative; display: inline-block; height: 100%; width: 25%; background-color: blue;">
        <p>1</p>
        <p>2</p>
        <p>3</p>
        <p>4</p>
    </div><div style="position: relative; display: inline-block; height: 100%; width: 25%; background-color: yellow;">
        <p>1</p>
        <p>2</p>
    </div><div style="position: relative; display: inline-block; height: 100%; width: 25%; background-color: green;">
        <p>1</p>
        <p>2</p>
        <p>3</p>
        <p>4</p>
        <p>5</p>
    </div><div style="position: relative; display: inline-block; height: 100%; width: 25%; background-color: pink;">
        <p>1</p>
        <p>2</p>
    </div>
</div>

And if you want the parent container div to encompass the children divs, add overflow:auto.

Upvotes: 4

Related Questions