How to force inline-block elements to wrap?

2019-02-16 12:39发布

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).

4条回答
一纸荒年 Trace。
2楼-- · 2019-02-16 12:54

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楼-- · 2019-02-16 13:01

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;");
查看更多
▲ chillily
4楼-- · 2019-02-16 13:10

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

查看更多
狗以群分
5楼-- · 2019-02-16 13:11

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.

查看更多
登录 后发表回答