Jon
Jon

Reputation: 74

CSS Centering content with float left and multiple rows

I have a site where I am displaying products. I want the products to fit as many on one line as the set width and margins will allow. I want it to have the items float left (at least have the last items float left), however I also want them centered.

Code (fiddle):

ul {
  list-style-type: none;
  margin: 0px;
  padding: 0px;
  overflow: hidden;
}
li {
  list-style-type: none;
  float: left;
  width: 150px;
  height: 150px;
  margin: 20px;
  padding: 3px;
  background: #CCCCCC;
  text-align: center;
}
li img {
  max-width: 144px;
}
<ul>
  <li><img src="" /></li>
  <li><img src="" /></li>
  <li><img src="" /></li>
</ul>
<ul>
  <li><img src="" /></li>
  <li><img src="" /></li>
  <li><img src="" /></li>
</ul>
<ul>
  <li><img src="" /></li>
  <li><img src="" /></li>
  <li><img src="" /></li>
  <li><img src="" /></li>
</ul>

As shown on jsfiddle, this is what I essentially have but want the products (represented by the boxes) to also be centered in the page.

Upvotes: 0

Views: 179

Answers (3)

Verhaeren
Verhaeren

Reputation: 1661

My solution, trying to preserve your code, is wrapping everything inside a div with a fixed width and margin set to auto:

HTML

<div>

<ul>
    <li><img src="" /></li>
    <li><img src="" /></li>
    <li><img src="" /></li>

    <li><img src="" /></li>
    <li><img src="" /></li>
    <li><img src="" /></li>

    <li><img src="" /></li>
    <li><img src="" /></li>
    <li><img src="" /></li>
    <li><img src="" /></li>
</ul>

</div>

CSS

ul { list-style-type:none; margin:0; padding:0;overflow:hidden;}
li { list-style-type:none;float:left; width:150px; height:150px; margin:20px; padding:3px; background:#CCCCCC; text-align:center; }
img { max-width:144px; }
div{margin: auto;width: 590px;}

FIDDLE

http://jsfiddle.net/33baohc7/1/

Upvotes: 0

Or Duan
Or Duan

Reputation: 13810

Try this, I changed your css:

<style type="text/css">
    ul { list-style-type:none; margin:0px; padding:0px; overflow:hidden; text-align: center;}
    li { list-style-type:none; display: inline-block; width:150px; height:150px; margin:20px; padding:3px; background:#CCCCCC; text-align:center; }
    li img { max-width:144px; }
    ul { text-align: center; }
</style>

Upvotes: 0

Oriol
Oriol

Reputation: 288170

You can try display: inline-block instead of float: left:

ul {
  text-align: center;
}
li {
  display: inline-block;
}

ul {
  margin: 0px;
  padding: 0px;
  text-align: center;
}
li {
  display: inline-block;
  width: 150px;
  height: 150px;
  margin: 20px;
  padding: 3px;
  background: #CCCCCC;
}
li img {
  max-width: 144px;
}
<ul>
  <li><img src="" /></li>
  <li><img src="" /></li>
  <li><img src="" /></li>
</ul>
<ul>
  <li><img src="" /></li>
  <li><img src="" /></li>
  <li><img src="" /></li>
</ul>
<ul>
  <li><img src="" /></li>
  <li><img src="" /></li>
  <li><img src="" /></li>
  <li><img src="" /></li>
</ul>

Upvotes: 1

Related Questions