27

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;
}
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Jonas
  • 19,422
  • 10
  • 54
  • 67

4 Answers4

56

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/

MaX
  • 1,765
  • 13
  • 17
  • 3
    Beware that making cards `inline-block` may affect the size of the space between each card. Some browsers, like Firefox, will add an extra space character between each card written literally in the HTML, because of the whitespace between the tags. – Rory O'Kane Jul 04 '13 at 06:08
  • 2
    @RoryO'Kane That's true. From looking at his code, there's no whitespace between spans, so it should be fine. It is something to be aware of, though. – MaX Jul 04 '13 at 09:21
2

Try adding this to your CSS:

.cards {
    white-space: nowrap;
    float: left;
}
omma2289
  • 54,161
  • 8
  • 64
  • 68
1

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.

Rory O'Kane
  • 29,210
  • 11
  • 96
  • 131
1

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

Alexander
  • 2,457
  • 1
  • 14
  • 17