简体   繁体   English

<span>在容器中</span>制作多个<span>自动中断线</span>

[英]make multiple <span> auto break line in a container

My question is as shown from here: jsfiddle demo 我的问题如下所示: jsfiddle演示

As you can see, the <span> element will automatically break line if I put each <span> on a new line in the html file. 如您所见,如果我将每个<span>放在html文件的新行中,则<span>元素将自动换行。

But, if I put them one by one together, they will not break line. 但是,如果我将它们一一放在一起,它们将不会折线。

Please Note, why I asked this question is because in my real project, I added the <span> from my js code dynamically. 请注意,为什么我问这个问题是因为在我的真实项目中,我从js代码中动态添加了<span> That will cause the same problem, which is that the <span> can't automatically break line, and will add a horizontal scrollbar when the number of them increased. 这将导致相同的问题,即<span>不能自动换行,并且当它们的数量增加时将添加水平滚动条。

Any suggestion will be highly appreciated. 任何建议将不胜感激。

ps I'm using Jquery and Bootstrap 3 in my code. ps我在代码中使用了Jquery和Bootstrap 3。

You can make your span tags acts like inline-block elements. 您可以使span标签的行为类似于inline-block元素。 They will display inline but if they does not fit on the container they will go to the next line. 它们将显示inline但是如果它们不适合容器,则将转到下一行。

span{
   display: inline-block !important;
}

Updated JSFiddle . 更新了JSFiddle

DEMO DEMO
Since No body mentioned it I'm going to add this: 由于没有人提到它,因此我将添加以下内容:
If you just append &nbsp; 如果您只是追加&nbsp; a html space entity or a even a normal space ' ' everything will work. 一个html空间实体,甚至一个普通空间' '都可以正常工作。

 $(document).ready(function () {
    var $well = $('<div class="well"/>');
    for(var i=0; i<20; i++){

        var $span = $('<span class="label label-warning"/>');
        $span.html("hello world!");
        $well.append($span);
        //this will work but will add an additional space $well.append(' &nbsp; ');
        $well.append(' ');
    }
    $('body').append($well);
});

Yes, you do need to apply an inline-block to the spans within the targeted div . 是的,您确实需要对目标div内的范围应用行inline-block You'll want to declare the specificity though to ensure that it only targets the spans within the .well container. 但是,您将要声明特异性,以确保它仅针对.well容器内的跨度。 Else, all of the spans with that class attribute will be affected on the web page. 否则,具有该class属性的所有spans将在网页上受到影响。

In your CSS, add the following: 在您的CSS中,添加以下内容:

.well span.label {
  display: inline-block;  
}
  • You do not need to force it with an !important . 您无需使用!important强制使用它。
  • While you can specify a maximum width, why would you? 尽管可以指定最大宽度,但为什么呢? Just let the text determine the width. 只需让文本确定宽度即可。

Updated JSFiddle 更新了JSFiddle

Use the property display:inline-block and set max-width to your span. 使用属性display:inline-block并将max-width设置为您的跨度。

https://jsfiddle.net/oubgpy8m/16/ https://jsfiddle.net/oubgpy8m/16/

.label{
  display: inline-block !important;
  width: 120px;
  margin:5px;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM