3

I have two divs with inline-block style, that both contains text with different font-sizes. They should be on the same line and then the second should break, but they are only if the second div is shorter then the body's width.

JSFiddle

div {
  display: inline-block;
  font-family: Arial;
}
#a {
  font-size: 30px;
  margin-right: 50px;
}
#b {
  /* No new line at b!! */
  font-size: 40px;
}
<div id="a">Fruits:</div>
<div id="b">Banana (3), Apple (2), Kiwi (5), Orange (1), Pear (11)</div>

Here I illustrate the problem:

What it looks like:

Fruits:
Banana (3), Apple (2), Kiwi (5), Orange (1), Pear (11)

What it should look like:

Fruits:  Banana (3), Apple (2), Kiwi (5),
         Orange (1), Pear (11)

And again, one more example of what it shouldn't look like, but could if the div was inline:

Fruits:  Banana (3), Apple (2), Kiwi (5),
Orange (1), Pear (11)

Is there anyway I can fix this?

I have tried using white-space: nowrap and word-wrap: break-word, but none of them seems to work.

sergdenisov
  • 8,327
  • 9
  • 48
  • 63

2 Answers2

0

You could use display: table-cell for it, but then you should use padding instead margin, because:

Margin applies to all elements, except elements with table display types other than table-caption, table and inline-table.

JSFiddle

div {
  display: table-cell;
  font-family: Arial;
}
#a {
  font-size: 30px;
  padding-right: 50px;
}
#b {
  /* No new line at b!! */
  font-size: 40px;
}
<div id="a">Fruits:</div>
<div id="b">Banana (3), Apple (2), Kiwi (5), Orange (1), Pear (11)</div>
sergdenisov
  • 8,327
  • 9
  • 48
  • 63
  • Wait.. Found something.. the margin-right on #a doesn't work :/ –  Jan 20 '16 at 20:24
  • 1
    @Murplyx Margins do not work on table cells. You can try `padding` or `border-spacing`. See [Set cellpadding and cellspacing in CSS?](http://stackoverflow.com/q/339923/1529630) – Oriol Jan 20 '16 at 20:32
  • @Murplyx yes, as @Oriol said, you should use `padding` then. Improved my answer. – sergdenisov Jan 20 '16 at 20:38
0

Instead of using inline-blocks, you can

  1. Float the first item to the left.
  2. Make the second one establish a block formatting context (BFC) in order to prevent it from overlapping the former. A common way to establish BFCs is overflow: hidden.

div {
  font-family: Arial;
}
#a {
  float: left; /* Push to the left */
  font-size: 30px;
  margin-right: 50px;
}
#b {
  overflow: hidden; /* Establish BFC */
  font-size: 40px;
}
<div id="a">Fruits:</div>
<div id="b">Banana (3), Apple (2), Kiwi (5), Orange (1), Pear (11)</div>
Oriol
  • 274,082
  • 63
  • 437
  • 513