Corentin Branquet
Corentin Branquet

Reputation: 1576

Center with flexbox

I've this code :

body {
  margin: 0;
}

ul {
  margin: 0;
  padding: 0;
  list-style-type: none;
  position: fixed;
  top: 0;
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

li {
  margin: 0;
  padding: 0;
  width: 100%;
  background-color: lightblue;
  flex-grow: 1;
}

a {
  display: block;
}
<ul>
  <li><a href="#">Test 1</a></li>
  <li><a href="#">Test 2</a></li>
  <li><a href="#">Test 3</a></li>
  <li><a href="#">Test 4</a></li>
  <li><a href="#">Test 5</a></li>
</ul>

I want my links to be center vertically and horizontally. Plus they have to fit the <li> container.

Can you inherit the flex-grow property ?

Thanks for your help !

Upvotes: 2

Views: 64

Answers (3)

Brad
Brad

Reputation: 8698

The problem is that each list item(the child) is also containing a child(the link).

So add display:flex; to the li also, then you can use flex properties on the li.

body {
  margin: 0;
}
ul {
  margin: 0;
  padding: 0;
  list-style-type: none;
  position: fixed;
  top: 0;
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

li {
  margin: 0;
  padding: 0;
  width: 100%;
  background-color: lightblue;
  flex-grow: 1;
  display: flex;
  justify-content: center;
}

a {
  display: block;
  align-self:center;
}
<ul>
  <li><a href="#">Test 1</a></li>
  <li><a href="#">Test 2</a></li>
  <li><a href="#">Test 3</a></li>
  <li><a href="#">Test 4</a></li>
  <li><a href="#">Test 5</a></li>
</ul>

Upvotes: 0

nashcheez
nashcheez

Reputation: 5183

Just add a text-align: center to your li to center it, and a flex: 1 to your li and height: 100% to your a to make it occupy 100% of the height of its parent.

Try this:

body {
  margin: 0;
}

ul {
  margin: 0;
  padding: 0;
  list-style-type: none;
  position: fixed;
  top: 0;
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

li {
  margin: 0;
  padding: 0;
  width: 100%;
  background-color: lightblue;
  text-align: center;
  flex: 1;
}

a {
  display: block;
  height: 100%;
}
<ul>
  <li><a href="#">Test 1</a></li>
  <li><a href="#">Test 2</a></li>
  <li><a href="#">Test 3</a></li>
  <li><a href="#">Test 4</a></li>
  <li><a href="#">Test 5</a></li>
</ul>

Upvotes: 0

Pete
Pete

Reputation: 58462

Just make the li and a flex too

body {
  margin: 0;
}
ul {
  margin: 0;
  padding: 0;
  list-style-type: none;
  position: fixed;
  top: 0;
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

li {
  margin: 0;
  padding: 0;
  width: 100%;
  background-color: lightblue;
  flex-grow: 1;
  display: flex;
}

a {
  flex-grow: 1;
  align-items:center;
  justify-content:center;
  display:flex;
}
<ul>
  <li><a href="#">Test 1</a></li>
  <li><a href="#">Test 2</a></li>
  <li><a href="#">Test 3</a></li>
  <li><a href="#">Test 4</a></li>
  <li><a href="#">Test 5</a></li>
</ul>

Upvotes: 2

Related Questions