Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text-align: center; ignored for display: flex element?

Tags:

html

css

flexbox

For the following the anchor text isn't centered. If I change the anchor's display from flex to block then the text is centered. Why is this?

Ive only tested on Chrome so far.

<ul>
  <li><a href="#">Link</a></li>
  <li><a href="#">Link</a></li>
  <li><a href="#">Link</a></li>
  <li><a href="#">Link</a></li>
  <li><a href="#">Link</a></li>
  <li><a href="#">Link</a></li>
</ul>



*, *:before, *:after {
  -moz-box-sizing: border-box; 
  -webkit- box-sizing: border-box;   box-sizing: border-box;
 }

ul {
  display: flex;
  flex-flow: row wrap;
  padding: 0;
  width: 40%;
  margin: auto;
  border: 1px solid gold;
}
li {
  list-style-type: none;
}
a {
  background: grey;
  width: 200px;
  border: 1px solid red;
  text-align: center;
  display: flex;
}

http://codepen.io/anon/pen/dgmbH

like image 798
Evanss Avatar asked Oct 01 '22 18:10

Evanss


1 Answers

Note: Before you go ahead to read my answer, I would like you to notify that am not using any of the PROPRIETARY PREFIXES, if it doesn't work for you, its time to update your browser, or try adding the prefixes like -moz or -webkit and see if it works for you.

The correct way to do is to use display: flex; for the ul element and flex-grow on li elements...

ul {
  display: flex;
  padding: 0;
  width: 40%;
  margin: auto;
  border: 1px solid gold;
}

li {
  list-style-type: none;
  flex-grow: 1;
}

Demo

You are using a fixed width on a tag i.e width: 200px; and that kills the idea of flex layout, so take that out, and alter your CSS with the one provided by me.

Here, I've used flex-grow with a value of 1 so that each of the li element shares the equal amount of width


If you are looking to wrap the cells if they exceed the containers width, than you need to use the following properties on ul element like

ul {
  display: flex;
  padding: 0;
  width: 40%;
  margin: auto;
  border: 1px solid gold;
  flex-direction: row;
  flex-flow: row wrap;
}

Demo (Resize your window to see the effect)

enter image description here

Sample 1, the wrapped element will stretch to full width


enter image description here

Sample 2, Elements wrapped equally further

Also note that am using min-width: 100px; on li elements to force wrap in the demonstration


As you commented that you wanted three li on each row, than instead of using flex-grow: 1; you need to use flex: 1 1 33%; like

li {
  list-style-type: none;
  flex-grow: 1;
  min-width: 100px;
  flex: 1 1 33.33%;
}

Demo

enter image description here

Sample 3, Equal number of li on each row

enter image description here

Sample 4, Equal number of li on each row even when resized

On further resize, they will accommodate automatically say two in a row and one in a row..

like image 157
Mr. Alien Avatar answered Oct 04 '22 15:10

Mr. Alien