HTML Element Style How to - Set margin based on child index








Question

We would like to know how to set margin based on child index.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
nav {<!--from   w ww .  j a  va  2s. c o  m-->
  height: 100%;
}

nav ul {
  margin: 0;
  padding: 0;
}

nav li {
  display: inline-block;
  font-size: 3em;
  text-transform: uppercase;
  background-color: #d0d0d0;
}

nav li:nth-child(2), nav li:nth-child(3) {
  margin-left: .25em;
}

nav a {
  color: #dddddd;
  text-decoration: none;
  font-family: arial;
  letter-spacing: -4.5px;
  margin: 0 4.5px 0 0;
}

nav a:hover, .selected {
  color: black;
}
</style>
</head>
<body>
  <nav class="padding_bottom">
    <ul>
      <li><a class="selected" href="#">Home</a></li>
      <li><a href="#">Music</a></li>
      <li><a href="#">Contact</a></li>
    </ul>
  </nav>
</body>
</html>

The code above is rendered as follows: