CSS two div width 50% in one line with line break in file

117,531

Solution 1

The problem is that when something is inline, every whitespace is treated as an actual space. So it will influence the width of the elements. I recommend using float or display: inline-block. (Just don't leave any whitespace between the divs).

Here is a demo:

div {
  background: red;
}
div + div {
  background: green;
}
<div style="width:50%; display:inline-block;">A</div><div style="width:50%; display:inline-block;">B</div>

Solution 2

The problem is that if you have a new line between them in the HTML, then you get a space between them when you use inline-table or inline-block

50% + 50% + that space > 100% and that's why the second one ends up below the first one

Solutions:

<div></div><div></div>

or

<div>
</div><div>
</div>

or

<div></div><!--
--><div></div>

The idea is not to have any kind of space between the first closing div tag and the second opening div tag in your HTML.

PS - I would also use inline-block instead of inline-table for this

Solution 3

Wrap them around a div with the following CSS

.div_wrapper{
    white-space: nowrap;
}

Solution 4

Give this parent DIV font-size:0. Write like this:

<div style="font-size:0">
  <div style="width:50%; display:inline-table;font-size:15px">A</div>
  <div style="width:50%; display:inline-table;font-size:15px">B</div>
</div>

Solution 5

How can i do something like that but without using absolute position and float?

Apart from using the inline-block approach (as mentioned in other answers) here are some other approaches:

1) CSS tables (FIDDLE)

.container {
  display: table;
  width: 100%;
}
.container div {
  display: table-cell;
}
<div class="container">
  <div>A</div>
  <div>B</div>
</div>

2) Flexbox (FIDDLE)

.container {
  display: flex;
}
.container div {
  flex: 1;
}
<div class="container">
  <div>A</div>
  <div>B</div>
</div>

For a reference, this CSS-tricks post seems to sum up the various approaches to acheive this.

Share:
117,531
Chris
Author by

Chris

Updated on July 08, 2022

Comments

  • Chris
    Chris about 2 years

    I try to build fluid layout using percentages as widths. Do do so i tried this:

    <div style="width:50%; display:inline-table;">A</div>
    <div style="width:50%; display:inline-table;">B</div>
    

    In that case they wont stand in one line, but if i remove line break between them, like this:

        <div style="width:50%; display:inline-table;">A</div><div style="width:50%;   display:inline-table;">B</div>
    

    then it works fine. Where is the problem? How can i do someting like that but without using absolute position and float.

    p.s. sorry for english. p.s.s. i hope i good explain my problem