rthrdyjd ryjrydjg
rthrdyjd ryjrydjg

Reputation: 73

CSS/HTML Boxes side by side

Having some problems getting my 4 grey boxes all displayed on the same line. Thought by giving them each a 25% width they would automatically each display a 1/4 screen size no matter ones resolution or screen size. Get the first 3, but the fourth one drops down on the next line. Any ideas on how to force them all on the same line?

HTML

<div class="b1"></div>
<div class="b2"></div>
<div class="b3"></div>
<div class="b4"></div>

CSS

.b1, .b2, .b3, .b4 {
   display:inline-block;
   position: relative;
   margin: 5px;
   float:left;
   width:25%;
   height:400px;
   background-color: lightgrey;
}

Upvotes: 5

Views: 35212

Answers (3)

incutonez
incutonez

Reputation: 3331

Take a look at the CSS Box Model. The reason why they're not floating side by side on the same line is because you're adding a margin. This margin is not considered in the height or width of your content area. If you used something other than margin, you could use the box-sizing property, but that's not the best approach. Ideally, you'd compensate for your margin, so something like this jsFiddle should get you started.

Obligatory addition: the widths add up to 92% leaving 8% to work with, so if you add a margin-left of 1% and margin-right of 1%, that gets multiplied by 4 items using the margin property (gives you 8% for the required width), you've got all 100% width accounted for.

HTML

<div class="b"></div>
<div class="b"></div>
<div class="b"></div>
<div class="b"></div>

CSS

.b {
    display: inline-block;
    position: relative;
    margin: 1%;
    float: left;
    width: 23%;
    height: 400px;
    background-color: lightgrey;
}

Upvotes: 5

Darren
Darren

Reputation: 13128

Give this a shot HTML

<div class="b1"></div>
<div class="b2"></div>
<div class="b3"></div>
<div class="b4"></div>

CSS

.b1, .b2, .b3, .b4{
    display:inline-block;
    position: relative;
    margin: 5px;
    float:left;
    width: calc(25% - 10px);
    height:400px;
    background-color: lightgrey;
}

As you can see with the width, we use calc() and use the original 25% width minus the 10px of margin you have left and right.

Upvotes: 2

Ken Hannel
Ken Hannel

Reputation: 2748

Your margin is what is causing the issue. Look at it this way, each of the 4 divs requires 25% of the page width PLUS a 5 pixel left margin and a 5 pixel right margin. So your margins either need to be percentage based or you need to decrease the percentage width of each div to allow for the margin.

Upvotes: 1

Related Questions