How to force inline-block elements to wrap?

2019-02-16 12:59发布

问题:

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:

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.



回答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.



回答3:

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;");


回答4:

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