22

I have an inline-block div.

.element {
display: inline-block;
}

I use jquery to repeatedly append it to the DOM.

  var element = $("<div class='element'>");
  $(body).append(element).append(element).append(element).append(element);

However the appended divs do not wrap. It is as if I had the following mark-up (no newlines)

<div class="element"></div><div class="element"></div><div class="element"></div><div class="element"></div>

Appending whitespace inbetween the elements does not fix problem:

  $(body).append(element).append(" ");

How can I force these elements to wrap? (I do not want to use floats).

1
  • Why not just turn your elements into blocks (or leave them like that actually, as that is the default for a div). Inline-block is rarely a good idea... Perhaps you should try to show what you are trying to achieve, or even set up a small fiddle (no need for the js there, just use your output, this is clearly a css issue)
    – Pevara
    Commented Jan 23, 2013 at 19:23

4 Answers 4

35

If they are simply div elements set to inline-block they should wrap like so: http://jsfiddle.net/72cYy/

Check and be sure their container/parent element does not have a white-space:nowrap. That would cause them to not wrap.

3
  • 7
    By default chrome does not wrap inline-block elements, use white-space:pre-wrap Commented Jul 13, 2014 at 3:00
  • This is what I want but i want the divs to be centered in the parent div, what should i add? Commented Aug 21, 2015 at 4:10
  • This is not the answer because inline-blocks width less than 50% do no wrap Commented Jun 18, 2023 at 18:08
2

You can give the elements width in terms of percentage. Change the percentage value with regard to the number of elements and how you want to wrap it.

0

I would recommend styling the element class with css to create the whitespace. If you don't want to do this you can always try to append a non-breaking space.

var element = $("<div class='element' />&nbsp;");
1
  • Unfortunately I already tried that. .element:after { content : "\a" } does not work with inline block Commented Jan 23, 2013 at 19:31
0

Alternatively, if the ::before pseudo element isn't being used, you can utilize it's powers to solve this issue.

element:before { /* single : to support older browsers */
    display:block;
    width:100%;
}

this is a solution for inline elements

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.