user2039981
user2039981

Reputation:

Two inline-blocks with text automatically break line

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.

Upvotes: 3

Views: 1111

Answers (2)

sergdenisov
sergdenisov

Reputation: 8572

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>

Upvotes: 0

Oriol
Oriol

Reputation: 288130

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>

Upvotes: 0

Related Questions