如何避免使用`inline-block`元素换行

时间:2015-12-28 07:08:06

标签: html css line-breaks

使用以下代码

CSS

.inline{display: inline-block;}

HTML

<div>
  X&nbsp;<div class="inline">Foo</div>
  X&nbsp;<div class="inline">Foo</div>
  X&nbsp;<div class="inline">Foo</div>
  X&nbsp;<div class="inline">Foo</div>
  X&nbsp;<div class="inline">Foo</div>
  X&nbsp;<div class="inline">Foo</div>
  X&nbsp;<div class="inline">Foo</div>
  X&nbsp;<div class="inline">Foo</div>
</div>

我打算避免在&nbsp;"X"div"Foo"之间的换行符(但允许div之间的换行符带有"Foo"的项目和以下"X")。

this demo所示,换行确实会发生。这是为什么?

在这种情况下如何避免换行?

4 个答案:

答案 0 :(得分:1)

    <style>
.inline{display: list-item;}

</style>

<div>
  X &nbsp;<div class="inline">Foo</div>
  X &nbsp;<div class="inline">Foo</div>
  X &nbsp;<div class="inline">Foo</div>
  X &nbsp;<div class="inline">Foo</div>
  X &nbsp;<div class="inline">Foo</div>
  X &nbsp;<div class="inline">Foo</div>
  X &nbsp;<div class="inline">Foo</div>
  X &nbsp;<div class="inline">Foo</div>
</div>



<div>
  <div class="inline">X &nbsp;Foo</div>
  <div class="inline">X &nbsp;Foo</div>
  <div class="inline">X &nbsp;Foo</div>
  <div class="inline">X &nbsp;Foo</div>
  <div class="inline">X &nbsp;Foo</div>
  <div class="inline">X &nbsp;Foo</div>
  <div class="inline">X &nbsp;Foo</div>
</div>

你可以使用Like this和它为我工作

答案 1 :(得分:-2)

只需用一个父div包装你的代码,它就会解决你的问题: -

只需用以下内容替换您的HMTL: -

<div>X&nbsp;<div class="inline">Foo</div></div>
<div>X&nbsp;<div class="inline">Foo</div></div>
<div>X&nbsp;<div class="inline">Foo</div></div>
<div>X&nbsp;<div class="inline">Foo</div></div>
<div>X&nbsp;<div class="inline">Foo</div></div>
<div>X&nbsp;<div class="inline">Foo</div></div>
<div>X&nbsp;<div class="inline">Foo</div></div>

它可能对你有帮助。

答案 2 :(得分:-2)

HTML引擎保留空格。

以此为例:

    <!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>

    <style>
        * {
            font-size: 40px;
        }

        span{
            margin: 0;
            padding: 0;
            border: 3px solid red;
        }

    </style>

</head>
<body>

    <span>Why are there spaces (margin & padding =0)</span>
    <span>between</span>
    <span>the inline elements?</span>
</body>
</html>

在浏览器中打开它,您会发现内联元素之间存在差距。

为了避免它全部写入一行

答案 3 :(得分:-2)

认为这将是肝脏:

<div>
  <div class="wrap">
    X&nbsp;<span class="inline">Foo</span>
  </div>
    <div class="wrap">
    X&nbsp;<span class="inline">Foo</span>
  </div>
    <div class="wrap">
    X&nbsp;<span class="inline">Foo</span>
  </div>
  <div class="wrap">
    X&nbsp;<span class="inline">Foo</span>
  </div>
  <div class="wrap">
    X&nbsp;<span class="inline">Foo</span>
  </div>
  <div class="wrap">
    X&nbsp;<span class="inline">Foo</span>
  </div>
  <div class="wrap">
    X&nbsp;<span class="inline">Foo</span>
  </div>
</div>

和css:

.wrap { display: inline-block; whitespace: nowrap;}

这是fiddle

关键是将X foo代码保持为块(内联块),这样您就可以应用空格规则并使内部div成为一个跨度,使其成为内联或阻塞。

希望这会有所帮助;)