Nicholas Haley
Nicholas Haley

Reputation: 4024

How to Center Cards within Div While Maintaining a Left-Align

I am currently building an app making use of cards. I would like the cards to be centered horizontally within the container, however the last row should be aligned left. Websites such as Yummly (http://www.yummly.com/) achieve this when you resize the page.

This is what I have so far, except I would like the blue squares to be center aligned within the orange container while maintaining the exact same configuration: http://jsfiddle.net/s8mfbeyt/13/

.container {
  width: 350px;
  height: 100%;
  background-color: red;
}
ul {
  list-style-type: none;
  padding: 0px;
}
li {
  height: 100px;
  width: 100px;
  background-color: blue;
  display: inline-block;
}
<div class="container">
  <ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
  </ul>
</div>

Thanks!!

Upvotes: 1

Views: 2654

Answers (2)

vals
vals

Reputation: 64254

You can get this effect setting some li fillers.

They take width, so that the last true li will be pushed to the left, but they have 0 height so visually everything is ok.

You need as many of them as the maximum number of columns that your design can get, minus 1.

I hate setting fake DOM elements, but it works ...

.container {
  width: 350px;
  height: 100%;
  background-color: red;
}
ul {
  list-style-type: none;
  padding: 0px;
  text-align: center;
}
li {
  height: 100px;
  width: 100px;
  background-color: blue;
  display: inline-block;
}
.dummy {
    height: 0px;
}
<div class="container">
  <ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li class="dummy"></li>
    <li class="dummy"></li>
  </ul>
</div>

Upvotes: 1

Paulie_D
Paulie_D

Reputation: 115309

There is a relatively new property (still partly experimental) text-align-last

.container {
  width: 350px;
  height: 100%;
  background-color: red;
}
ul {
  list-style-type: none;
  padding: 0px;
  text-align: center;
  -ms-text-align-last: left;
  -webkit-text-align-last: left;
  -moz-text-align-last: left;
  text-align-last: left;
}
li {
  height: 100px;
  width: 100px;
  background-color: blue;
  display: inline-block;
}
<div class="container">
  <ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
  </ul>
</div>

Works in FF & IE (but WebKit based browsers are bugged at the moment)

Text-Align-Last @ MDN

Browser Support @ CanIUs.com

Upvotes: 1

Related Questions