Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS/HTML Boxes side by side

Tags:

html

css

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;
}
like image 867
rthrdyjd ryjrydjg Avatar asked Sep 26 '13 23:09

rthrdyjd ryjrydjg


2 Answers

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;
}
like image 66
incutonez Avatar answered Sep 21 '22 12:09

incutonez


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.

like image 20
Darren Avatar answered Sep 21 '22 12:09

Darren