Alberto Rossi
Alberto Rossi

Reputation: 1800

CSS center align ul list

I have a <ul> list on my website that contains some sub menus. It is structured in this way:

<div id="cssmenu">
<ul>
   <li class='active'><a href='index.html'><span>Home</span></a></li>
   <li class='has-sub'><a href='#'><span>RNG</span></a>
      <ul>
         <li><a href='#'><span>menu 1</span></a></li>
         <li><a href='#'><span>menu 1</span></a></li>
         <li class='last'><a href='#'><span>menu 1</span></a></li>
      </ul>
   </li>
   <li class='has-sub'><a href='#'><span>Altro</span></a>
      <ul>
         <li><a href='#'><span>kldajofa</span></a></li>
         <li class='last'><a href='#'><span>Altro12</span></a></li>
      </ul>
   </li>
   <li class='last'><a href='#'><span>Contact</span></a></li>
</ul>
</div>

I have 4 <li> as you can see and I'd like to see them center-aligned with the width of the screen, but I don't know how to do it.

You can see a fiddle here that contains the CSS too. How can center align the names I have on my menu?

enter image description here

Upvotes: 1

Views: 1978

Answers (4)

Paulie_D
Paulie_D

Reputation: 114991

If the li are display:inline-block you can apply text-align:center to the ul and the list items will center regardless of the number (provided there is room on the line).

The good news is that there are no clearing issues.

JSFiddle

Upvotes: 1

Josh Crozier
Josh Crozier

Reputation: 240868

Assuming there are only 4 li - as in the example, set width:25%.

Working jsFiddle here

#cssmenu li {
    float: left;
    padding: 0px;
    width: 25%;
}

enter image description here

I made a minor update so that the sub-nav menu items are also 25%..

jsFiddle here

There were set to width:225px;.

#cssmenu li ul {
    width: 25%;
}

Upvotes: 2

Ahmad Alfy
Ahmad Alfy

Reputation: 13371

Considering you have only 4 menu items, you just need to add :

#cssmenu > ul > li { width:25%; }

This will set the width of the list items to 25%. And since the a are set to be displayed as blocks, they will fit the whole width of the li.

Note that we are using the direct child selector > because we don't want this effect to be applied to the menu lis inside the sub-menu. We only need that effect on the root level.

Other possible solution is to use flexbox which isn't well supported yet and cannot be used without polyfill.

Upvotes: 1

Aycan Yaşıt
Aycan Yaşıt

Reputation: 2104

I've just added width to li and it works now.

Check JsFiddle

#cssmenu li a {
  background: #0D0D0D bottom right no-repeat;
  display: block;
  font-weight: normal;
  line-height: 35px;
  margin: 0px;
  padding: 0px 25px;
  text-align: center;
  text-decoration: none;
    width:70px;
}

Upvotes: -1

Related Questions