How to keep <li> elements on single line in fixed width <ul>?

瘦欲@ 提交于 2019-12-05 11:15:46
LinkinTED

I edited a whole lot in your CSS, check the updated fiddle.

Basicly, this is what I've done:

HTML:

<ul>
    <li><a href="#">link</a></li>
    <li><a href="#">link</a></li>
    <li><a href="#">link</a></li>
</ul>

CSS:

ul {
    width: 960px;
    display: table;
    table-layout: fixed;
}
ul li {
    display: table-cell;
}
ul li a {
    display: block;
}

The ul is displayed as a table, with the li's as table-cells, making it as width as the header. Within the li i display the anchors as a block, making them fill the whole li. Hope it suits you.

P.s. make sure you remove the class cf from the ul when you use this.

Fable4Life

I think some fellow frustrates may find this useful:

.main-menu ul li ul li{
  white-space: nowrap;
}

Like this

ul#mmenu li
{
padding:7px;
}

DEMO

You'll need to adjust the padding in ul#mmenu I changed the padding to padding:7px 23px; and it stays in a single line,but there will be a blank space at the right end of the last menu.

You can give absolute position to li items and position them (first have left:0, second: left:100px or so... last have right:0 and so on). That way they will always be at the same place when you zoom.

For those wanting to avoid CSS table and table-cell, which by the way, I have no probelm with you can use text-align:justify on the UL with a couple of tweaks.

Basic HTML:

<ul id='mmenu'>
   <li><a href='#'>Blah Blah Blah Blah</a></li>
   <li><a href='#'>Blah Blah</a></li>
   <li><a href='#'>Blah Blah Blah Blah</a></li>
   <li><a href='#'>Blah Blah</a></li>
</ul>

Note we've lost the clearfix because: a) We're not going to use floats and b)it breaks this solution.

CSS:

ul#mmenu{
   width:100%;
   margin:15px 0 10px 0;
   overflow:hidden;
   text-align:justify; /*Added this*/
}

ul#mmenu li{
   letter-spacing:.05em;
   color:#0a93cd;
   /*Now inline blocks instead of blocks floated left*/
   display:inline-block; 
   font:24px arial;
   padding:7px 26px;
   background:#fff;
   border-left:2px solid #0a93cd;
   border:2px solid #0a93cd;
   border-radius:13px;
   text-align:center;
}

/*Now for the hacky part....
  ...justify does not, by design, justify the last row of text
  therfore we need to add an additional, invisible line*/
ul#mmenu:after {
   content: "";
   width: 100%;
   display: inline-block;
}

I have also removed the :first-child style in the Updated Fiddle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!