whitespace nowrap css for children but not parent
Asked Answered
L

3

6

I have a div with multiple spans inside. The spans contain text that cannot be split over multiple lines so I have set whitespace: nowrap. This does stop the wrapping within each child span correctly but also stop the parent div from wrapping the children so all spans are on a single line that stretches off the page.

How do I change this behaviour so the nowrap only applies to the contents of each span?

Lobate answered 15/10, 2010 at 16:16 Comment(0)
B
6

Option 1

<style>
   .nowrap { white-space: nowrap; }
</style>

<div>
   <span class="nowrap">span 1</span>
   <span class="nowrap">span 2</span>
   <span class="nowrap">span 3</span>
   <span class="nowrap">span 4</span>
   <span class="nowrap">span 5</span>
</div>

Option 2

<style>
   .myDiv span{ white-space: nowrap; }
</style>

<div class="myDiv">
   <span>span 1</span>
   <span>span 2</span>
   <span>span 3</span>
   <span>span 4</span>
   <span>span 5</span>
</div>
Brantley answered 15/10, 2010 at 16:20 Comment(5)
I think the OP wants to avoid having to add the class to every single element. See my answer.Depict
or give the div an id, and just do id_of_div span{white-spave:nowrap;}Underground
@Cfreak, I was already thinking that (hence, "Option 1"). I have added Option 2.Brantley
This solution does not work in IE8 or IE9. See my question http://stackoverflow.com/questions/7877095Breughel
I'm using option 2 but for some reason my spans all on one line and overflow my div container.Thane
D
2
div#id-of-parent span {
    whitespace: nowrap;
}

That should do the trick. (your div will need the id attribute on it.)

Depict answered 15/10, 2010 at 16:20 Comment(2)
if you already have an id, there shouldn't be a need for the tag element.Underground
@Underground - true but it's slightly faster for the browserDepict
H
1

Set the span elements to have display:inline-block.

Hawsehole answered 24/6, 2019 at 16:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.