Tomm Huth
Tomm Huth

Reputation: 235

CSS white-space: nowrap causes container to expand to fit all text

I'm experiencing a very strange behavior in which a an element with overflow: hidden, white-space: nowrap, and a width: 50% forces its containing element to expand to fit all the text even though it is constrained by the width declaration (and not actually visible). Setting a specific width on the container or using overflow: hidden also does nothing to help. Setting an absolute value as width for the element in question however, fixes the problem, but i do not want to use absolute values.

Example: http://jsbin.com/loxuz/3 (Yellow box should only be 50% of grey box, but is expanding to fit all of the text in the blue box, even though that is restricted in width.)

Does anyone see anything obviously wrong here? Should the containing elements have a width, and could it have anything to do with the fact that I'm using percentages? I don’t feel that could be the case as the width should be inherited from containers upwards, right? And not be dictated form text elements downwards. The only explanation I can find is that white-space: nowrap is causing this. Removing this gives the container the right width, but also causes wrapping of the text, which I don’t want.

Does anyone know a solution to this, or have any insight? :)

Upvotes: 14

Views: 12104

Answers (2)

hunthunthunt
hunthunthunt

Reputation: 171

A quick workaround for the issue with fieldsets not respecting the specified width is to add a min-width: 0 to the element:

i.e.

fieldset {
  min-width: 0;
}

Upvotes: 11

Dhiraj
Dhiraj

Reputation: 1871

Is this what you want? DEMO: http://jsbin.com/tifefase/1/. You should remove max-width: 50% from span and write width: 50% for #second div. This is the answer you are looking for if you want to use fieldset.

#second {
  width:50%; 
  border:yellow 1px solid;
}

span {
  overflow:hidden;
  white-space:nowrap;
  outline:blue 1px solid;
  display:block;
}

But if you use div instead of fieldset, You can carry on with your current values. SEE THE NEW DEMO with div being used instead of fieldset.

#second {
  width:50%; 
}

#third {
  width:100%; 
  border:yellow 1px solid;
}

Upvotes: 0

Related Questions