CSS - HTML Lists - center UL in page & left align LI items

Viewed 1347

I have this code:

.menu {
    margin: auto;
    padding: 0;
    list-style-type: none;
}
.item {
    width: 60px;
    text-align: center;
    font-size: 4em;
    background-color:red;
    display: inline-block;
    margin: 5px;
    padding: 25px;
}
<ul class="menu">
  <li class="item">1</li>
  <li class="item">2</li>
  <li class="item">3</li>
  <li class="item">4</li>
  <li class="item">5</li>
  <li class="item">6</li>
  <li class="item">7</li>
  <li class="item">8</li>
  <li class="item">9</li>
  <li class="item">10</li>
</ul>

I want to center align the entire ul container, while keeping the li items aligned to left.

So instead of this:

enter image description here

I want to have something like this:

enter image description here

I can't seem to make it work..

Any help would be appreciated.

Thanks in advance!

5 Answers

You can also try the following flex box solution:

* {
  margin: 0;
  padding: 0;
}

body {
  width: 100vw;
  height: 100vh;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.menu {
  position: relative;
  list-style: none;
  width: 80vw;
  display: flex;
  flex-flow: row wrap;
  justify-content: flex-end; 
  background: green;
}

.item {
  width: 15vw;
  height: 15vw;
  background: red;
  margin: 1vw;
  /*the following is only for styling the numbers*/
  font-size: 25px;
  display: flex;
  align-items: center;
  justify-content: center;
}
<ul class="menu">
  <li class="item">1</li>
  <li class="item">2</li>
  <li class="item">3</li>
  <li class="item">4</li>
  <li class="item">5</li>
  <li class="item">6</li>
  <li class="item">7</li>
  <li class="item">8</li>
  <li class="item">9</li>
  <li class="item">10</li>
</ul>

Try this:

.menu {
padding: 0;
list-style-type: none;
width: 500px; /* Change this value is you need more li in the same line. You can also use percents */
/*width: 90% */
display: block;
margin-right: auto;
margin-left: auto;
}
.item {
width: 60px;
text-align: center;
font-size: 4em;
background-color:red;
display: inline-block;
margin: 5px;
padding: 25px;
}

Since you are using pixels with .item, I think this will suites best:

.menu {
  min-width: 300px;
  max-width: 90%;
  margin: auto;
  padding: auto;
  list-style-type: none;
}
.item {
  width: 60px;
  text-align: center;
  font-size: 4em;
  background-color: red;
  display: inline-block;
  margin: 5px;
  padding: 25px;
}

Basically i just added measurements for the UL element. Hope i helped and Good Luck!

Try surounding you element in div (or whatever else) with display: flex. Margin: auto property only works on flex.

Related