Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap many <span> within <div>

Tags:

css

word-wrap

I have a <div> with hard-coded width. Inside the <div> are several hundred <span> tags. Can I wrap the spans so that line spacing is correct and wrapping is between spans? I use word-wrap: break-word and it looks a mess.

Here is pseudo code.

span {
  margin: 2px;
  border: 1px dotted #cccccc;
  padding: 4px 10px 4px 10px; 
    }
div {
  padding: 5px;
  margin: 5px;
  border: 1px solid #cccccc;
  width: 800px;
  word-wrap: break-word;
}

<div>
  <span>stuff</span>
  <span>more stuff</span>
  <span>even more stuff</span>
  .
  .
  .
</div>

Thanks!

EDIT for clarification: There should be multiple spans on each line, and wrapping should be between spans.

like image 955
user191688 Avatar asked Nov 25 '11 20:11

user191688


People also ask

Can we put span inside div?

span is an inline-element, while div ist not. you should consider swapping them..

Can span be nested?

The HTML span TagYou shouldn't nest span unless you thoroughly know what you're doing – but you can put multiple span tags within a block-level element.

How do I wrap text in a div?

If you've faced the situation when you need to wrap words in a <div>, you can use the white-space property with the "pre-wrap" value to preserve whitespace by the browser and wrap the text when necessary and on line breaks. Also, you'll need the word-wrap property.

How do you wrap a word in Span?

You can use the CSS property word-wrap:break-word; , which will break words if they are too long for your span width. Works well for the asp.net label control. Thanks!


2 Answers

EDIT (2017): Flexbox with wrap display: flex; flex-wrap: wrap is compatible with IE10+ (and Android 4.4+) and will allow versatile alignments both horizontally (justified, aligned to the left or right, space-around, centered) and vertically (align-items) with also versatile spacing between lines (align-content… if an height is set, in general).
Bonus: no ~4px whitespace between items to take care of as with inline-block. You do pretty much what you want: no gutter, flex: 1 1 auto or padding: 1rem for example
Cheatsheet for Flexbox on CSS Tricks
/EDIT

Span doesn't seem very semantic, maybe use an unordered list?

If I understood well your problem, you want as many span per line that'll fit but no span begininng on a line and finishing in another line?
Then the following fiddle: http://jsfiddle.net/MRR6P/ will do the trick. Try

span {
  line-height: 1.8;
  word-wrap: normal;
  display: inline-block;
}
like image 122
FelipeAls Avatar answered Sep 20 '22 19:09

FelipeAls


not 100% sure what you mean but if you want each span to display on a different line, then make them display block

span { display: block; }

edit

maybe

white-space:nowrap;

like this? http://jsfiddle.net/xNndp/1/ except with no width on the div of course

like image 37
Huangism Avatar answered Sep 22 '22 19:09

Huangism