2

My HTML

<div id="wrapper">
    <div id="div1">The two divs are</div>
    <div id="div2">next to each other.</div>
</div>

My CSS

#wrapper {
    border: 1px solid blue;
}
#div1 {
    display: inline-block;
    width:49%;
    height:120px;
    border: 1px solid red;
}
#div2 {
    display: inline-block;
    width:49%;
    height:160px;
    border: 1px solid green;
}

A JSFiddle

So, when as you can see the width of each div is 49%, that's the only way I'm getting it to work. If you set the width of each to 50%, the divs aren't displayed next to each other anymore... Why is that?

  • It is because you have a border of 1 px on each side. The box-model then makes the div 50% wide + 2px on each side, the 2px being your problem – Velimir Tchatchevsky Apr 13 '16 at 13:58
  • 1
    Possible duplicate of [Two inline-block elements, each 50% wide, do not fit side by side in a single row](http://stackoverflow.com/questions/18262300/two-inline-block-elements-each-50-wide-do-not-fit-side-by-side-in-a-single-ro) – Vucko Apr 13 '16 at 14:01
  • This question has been answered so many times here – dippas Apr 13 '16 at 15:17

5 Answers5

7

Because of two things

  1. Border size so you need to change box-sizing to border-box
  2. White space on inline-block elements

* {
  box-sizing: border-box;
}
#wrapper {
  border: 1px solid blue;
}
#div1 {
  display: inline-block;
  width: 50%;
  height: 120px;
  border: 1px solid red;
}
#div2 {
  display: inline-block;
  width: 50%;
  height: 160px;
  border: 1px solid green;
}
<div id="wrapper">
  <div id="div1">The two divs are</div><div id="div2">next to each other.</div>
</div>
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
1

You need to remove the line break between the <div> tags and box-sizing:border-box; The two divs arenext to each other.

Another approach would be to use float

    #wrapper {
        border: 1px solid blue;box-sizing:border-box;
    }
    #div1 {
        float:left;
        width:50%;
        height:120px;
        background:green;
box-sizing:border-box;
border:1px solid #909090;
    }
    #div2 {
        float:left;
        width:50%;
        height:160px;
        background:green;
box-sizing:border-box;
border:1px solid #909090;
    }
Rohit Agre
  • 1,528
  • 1
  • 14
  • 25
0

The other option is to use Flex.

#wrapper {
    border: 1px solid blue;
    display: flex;
}
#div1 {
    width:50%;
    height:120px;
    border: 1px solid red;
}
#div2 {
    width:50%;
    height:160px;
    border: 1px solid green;
}
0

This is because you have added a border of 1px to wrapper. Your border with take 2px of total width of your page.

If you wanna keep the border and still keep the width of each div as 50%, you can refer to @NenadVracar 's answer

Sandeep Sukhija
  • 1,156
  • 16
  • 30
0

Another option is to use calc() and calculate the width to be 50% - 2px. I'm just listing that as an option @Nenad Vracar has the right answer

Velimir Tchatchevsky
  • 2,812
  • 1
  • 16
  • 21