matt.mcg
matt.mcg

Reputation: 429

Center a block of images with CSS

Using the box model I’ve created a 3 by 3 grid of images. I wanted all the images centered so I wrapped all the images in a div and set the padding-left to 10%. This worked but I’m assuming it wasn’t the correct way of doing this, so I’m asking for someone to tell me what I should’ve done instead. HTML and CSS below…

img {
  width: 30%;
  float: left;
  margin: 0.1%;
  max-width: 700px;
}

.block {
  padding-left:10%;
}
<div class="block">
  <img src="placeholder.png">
  <img src="placeholder.png">
  <img src="placeholder.png">
  <img src="placeholder.png">
  <img src="placeholder.png">
  <img src="placeholder.png">
  <img src="placeholder.png">
  <img src="placeholder.png">
  <img src="placeholder.png">
</div>

Upvotes: 0

Views: 829

Answers (5)

raviramani
raviramani

Reputation: 522

update your css like this

block{
    display:flex;
    flex-wrap:wrap;
}
block img{
    width:33.33%;
}

Upvotes: 0

Surendra Pathak
Surendra Pathak

Reputation: 204

You can achieve that by using the following CSS:

.block {
    font-size: 0;
    text-align: center;
    margin: 0 auto;
}
img {
    display: inline-block;
    width: 30%;
    max-width: 700px;
    vertical-align: center;
    margin: 0.1%;
}

Upvotes: 1

WK5
WK5

Reputation: 330

.block {
    float: none;
    margin: 0 auto;
}

Upvotes: 0

Christopher Bradshaw
Christopher Bradshaw

Reputation: 2775

You probably want to use a CSS grid for this type of thing. Your CSS would look something like this for a 3x3 grid:

.block {
  display: grid;
  grid-template-rows: 1fr 1fr 1fr;
  grid-template-columns: 1fr 1fr 1fr;
}

Here's a working example

If you want to learn more about css grids there's also plenty of tutorials out there. If you don't know where to start, this one's pretty helpful though.

Upvotes: 1

wades
wades

Reputation: 292

Correct me if I’m wrong but this would centre the block would it not? Just add your padding to that...?

.block {
margin-left: auto;
margin-right: auto;
}

Upvotes: 0

Related Questions