-->

Don’t wrap span elements

2019-04-18 04:35发布

问题:

I’ve got a list of <span> elements that can be moved left and right inside a <div> element, and if some spans go outside the div they should be hidden. This works fine using overflow: hidden.  However, if there are more spans than fit in the div, the spans wrap, which is undesired behaviour for my use case. How do I make the spans not wrap?

I’ve made a jsFiddle to show what I mean. When you click inside the .board you’ll add another .card. By the fourth card you’ll see the wrapping.

Note: The fact that spans are used is not really important, so if it can be made to work with e.g. list items, that would probably be okay. The important thing is that the elements can contain an image and some text underneath.

Here’s the code from the jsFiddle:

<div class="board">
   <div class="cards"></div>
</div>
$('.board').mousemove(function(e) {
    $('.cards').css({left: e.pageX});
});

$('.board').click(function(e) {
   $('.cards').append("<span class='card'></span>") 
});
.card {
    border: 1px solid black;
    width: 100px;
    height: 100px;
    float: left;
    margin-left: 4px;
    margin-right: 4px;   
}  

.cards {
    position: relative;
    top: 10px; 
}

.board {
    width: 400px;
    height: 120px;
    border: 1px solid red;
    position: relative;
    overflow: hidden;
}

回答1:

You can use inline-block on .card in stead of float, and then disable wrapping with nowrap:

For .card:

display:inline-block;

For .cards:

white-space:nowrap;

http://jsfiddle.net/33kj4/1/



回答2:

You are trying to do 'block' layout with SPAN elements. SPAN elements are not suitable for block, that's what DIVs are for.



回答3:

Just set the width of .cards to some huge number:

.cards {
    position: relative;
    top: 10px;
    width: 99999%;
}

jsFiddle

The default width of .cards is constrained to the width of its parent .board, 400px. Most of the time, having a maximum width is good, because it causes children to wrap if necessary. But since you don’t mind overflow, it’s okay to override this.



回答4:

Try adding this to your CSS:

.cards {
    white-space: nowrap;
    float: left;
}