Eric Schumann
Eric Schumann

Reputation: 119

Divs not floating correctly. I'm not sure what I'm missing

I'm messing around with some css positioning for a class I'm taking and I'm having trouble putting two divs side by side using float.

When i use float left on the #first div the #second div doesn't move to the right of #first.

Not sure what I'm doing wrong.

Here's the HTML:

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="main.css">
    </head>
    <body>
        <div class="container">
            <div id="first">First</div>
            <div id="second">Second</div>
        </div>
    </body>
</html>

And here's the CSS:

html, body, div, p {
    padding: 0;
    margin: 0;
}
.container {
    border: 2px solid black;
    width: 1280px;
    height: 500px;
    margin: 10px auto 0;
}
.container div {
    margin: 5px;
    padding: 10px;
}
#first {
    border: 2px solid red;
    width: 25%;
    float: left;
}
#second {
    border: 2px solid green;
    width: 25%;
}

Upvotes: 0

Views: 35

Answers (1)

Richard Hamilton
Richard Hamilton

Reputation: 26444

divs by default are block elements, meaning they take up the full width of the screen. To fix this, simply add the display style inline-block to both divs.

html, body, div, p {
    padding: 0;
    margin: 0;
}
.container {
    border: 2px solid black;
    width: 1280px;
    height: 500px;
    margin: 10px auto 0;
}
.container div {
    margin: 5px;
    padding: 10px;
}
#first {
    border: 2px solid red;
    width: 25%;
    display: inline-block;
    float: left;
}
#second {
    border: 2px solid green;
    width: 25%;
    display: inline-block;
}
<div class="container">
  <div id="first">First</div>
  <div id="second">Second</div>
</div>

Upvotes: 1

Related Questions