简体   繁体   中英

How can I prevent display:table-cell elements from floating?

I have a list of li's which has display:table-cell property in order to vertically center the text inside. I can not use additional markup for this. I can not use line-height as there may be multiple lines of text.

When I give the li's to display:table-cell property, they float next to each other.

How can I force them to be below each other, like they would with display:block? Or I can't?

http://jsbin.com/orijam/1/edit

li {
  height:50px;
  border:solid black;
  vertical-align:middle;
  min-width:100px;
  display:table-cell;
}
ul {
  border:solid red;
  width:100px;
  display:inline-block;
}

Set the li :s to table-row and move the table-cell styling to your a elements (assuming you have a ul li a setup) (written on phone)

Edit: http://jsfiddle.net/Z7Sgg/

Edit2: If you're missing the a :s you could add them (or a span ) using JS:

$(function () {
    $('#menu li').wrapInner('<span></span>');
});

Use display:table instead of display:table-cell . It will work.

Use a span tag instead.

<li><span>li</span></li>
<li><span>li</span></li>

Here is the solution .

The HTML:

  <ul>
    <li><span>li</span></li>
    <li><span>li</span></li>
    <li><span>li</span></li>
    <li><span>li</span></li>
    <li><span>li</span></li>
    <li><span>li</span></li>
  </ul>

The CSS:

span {
  height:50px;
  border:solid black;
  min-width:100px;
    vertical-align:middle;
  display:table-cell;
}
ul {
  border:solid red;
  width:100px;
  display:inline-block;
}

ul li {display:block;}

By inseting a span tag inside the li, you can make sure that you can keep the vertical alignment middle for the li's as well as make them appear to be block.

Hope this helps now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM