Home > front end >  Centering non-text content in a center division?
Centering non-text content in a center division?

Time:06-30

In my page, I need to make something that looks like this, with a center division with images of different widths all center-aligned within the division (the lines won't be visible, that's just to make it easier to explain):

---------------------------------------
|           |   IMAGE 1   |           |
|  <stuff>  |   IMAGE 2   |  <stuff>  |
|           |  IMAGE 123  |           |
---------------------------------------

There's a parent division for the whole "pseudo-table", and three divisions for each pseudo-column. However, no matter what I try, it seems to always look like this, where the left edge of the images aligns with each other:

---------------------------------------
|           |  IMAGE 1    |           |
|  <stuff>  |  IMAGE 2    |  <stuff>  |
|           |  IMAGE 123  |           |
---------------------------------------

My HTML looks like this:

<div >
  <div >STUFF HERE</div>
  <div >
    <img="URL HERE"><br>
    <img="URL HERE"><br>
    <img="URL HERE">
  </div>
  <div >STUFF HERE</div>
</div>

For my CSS, I have pared it down for the sake of troubleshooting to:

.parent {
  display:flex;
  justify-content:space-between;
}
.leftcol {
}
.centercol {
  justify-items:center;
}
.rightcol {
}

I've also tried align-items:center to the same lack of results. Any ideas?

CodePudding user response:

Add display: flex, align-items: center and flex-direction: column to the center column div:

.parent {
  display:flex;
  justify-content:space-between;
}
.leftcol {
}
.centercol {
  display: flex;
  align-items: center;
  flex-direction: column;
}
.rightcol {
}
<div >
  <div >STUFF HERE</div>
  <div >
    <img src="https://picsum.photos/100"><br>
    <img src="https://picsum.photos/150/100"><br>
    <img src="https://picsum.photos/120/100">
  </div>
  <div >STUFF HERE</div>
</div>

CodePudding user response:

You may also imbricate flex and grid to allow also X,Y centering on each columns : example

.parent {
  display:flex;
}
.parent>div {
  flex:1;
  display:grid;
  justify-content:center;
  align-items:center;
  
  gap:0.25em;/* optionnal */
}
/* see what is going on */
div div {
  border:solid 1px;
  background:linear-gradient(90deg,transparent 50%, rgba(200,100,100,0.1) 50%),linear-gradient(0deg,transparent 50%, rgba(100,0,100,0.1) 50%)
}
<div >
  <div >STUFF HERE</div>
  <div >
    <img src="https://picsum.photos/50"><br>
    <img src="https://picsum.photos/50/40"><br>
    <img src="https://picsum.photos/60/30">
  </div>
  <div >STUFF HERE</div>
</div>

  • Related