Home > Enterprise >  CSS center list items horizontally and to right
CSS center list items horizontally and to right

Time:08-05

I'm having trouble with centering li so that they are both on the right site of navbar and are centered vertically. I want them to also not clip out of navbar when resized.

* {
  margin: 0;
  padding: 0;
  border: 0;
}

body {
  margin: 0 10vw;
  background-color: #E7E7E7;
}

.main-site {
  background-color: white;
}

.main-body {
  padding-top: 6vh;
}

nav,
.bottom-nav {
  position: fixed;
  background-color: red;
  height: 6vh;
  width: 80vw;
}

.nav-list {
  position: absolute;
  margin: 1% 0;
  right: 3vw;
}

.nav-items {
  list-style: none;
  right: auto;
  display: inline-block;
  font-size: 20px;
  padding: 0 1vw;
}
<div >
  <nav>
    <ul >
      <li ><a href=""> Item 1</a></li>
      <li ><a href=""> Item 2</a></li>
      <li ><a href=""> Item 3</a></li>
      <li ><a href=""> Item 4</a></li>
    </ul>
  </nav>
</div>

CodePudding user response:

You just need remove your view height for the nav and stop absolute positioning. Using flexbox, the nav css below will be responsive on resize.

* {
  margin: 0;
  padding: 0;
  border: 0;
}

body {
  margin: 0 10vw;
  background-color: #E7E7E7;
}

.main-site {
  background-color: white;
}

.main-body {
  padding-top: 6vh;
}

nav,
.bottom-nav {
  display:flex;
  justify-content: flex-end;
  margin-left: auto;
  background-color: red;
  width: 80vw;
}

.nav-list {
  margin: 1% 0;
  right: 3vw;
}

.nav-items {
  list-style: none;
  right: auto;
  display: inline-block;
  font-size: 20px;
  padding: 0 1vw;
}
<body>
  <div >
    <nav>
      <ul >
        <li ><a href=""> Item 1</a></li>
        <li ><a href=""> Item 2</a></li>
        <li ><a href=""> Item 3</a></li>
        <li ><a href=""> Item 4</a></li>
      </ul>
    </nav>
  </div>
</body>

CodePudding user response:

Use display flex on nav element, instead of brute absolute positioning :)

* {
  margin: 0;
  padding: 0;
  border: 0;
}

body {
  margin: 0 10vw;
  background-color: #E7E7E7;
}

.main-site {
  background-color: white;
}

.main-body {
  padding-top: 6vh;
}

nav {
  display: flex;
  align-items: center;
  justify-content: right;
}

nav,
.bottom-nav {
  position: fixed;
  background-color: red;
  width: 80vw;
}

.nav-list {
  display: flex;
}

.nav-items {
  list-style: none;
  right: auto;
  font-size: 20px;
  padding: 0 1vw;
}

.nav-items a {
  display: inline-block;
}
<div >
  <nav>
    <ul >
      <li ><a href=""> Item 1</a></li>
      <li ><a href=""> Item 2</a></li>
      <li ><a href=""> Item 3</a></li>
      <li ><a href=""> Item 4</a></li>
    </ul>
  </nav>
</div>

  • Related