Search code examples
htmlcsscss-multicolumn-layout

how to center an item when it's the only one in a multi-column layout


I'm pulling dynamic images into a 2-column layout. If there's only one image, how would I center it, or collapse the columns into one? Currently a single image is placed in the left column. Is there a CSS-only solution?

Would the same logic apply to the last item in a column, if it's the only one in its row?

p{
  column-count: 2;
  column-gap: 0;
}

p>img{
  display: block;
  width: 100%;
  height: auto;
  border: 3px solid transparent;
  box-sizing: border-box;
}

Thanks to Eric N's answer and column-span, the following added CSS centers the first and only item in a 2-column layout:

p>img:first-of-type:last-of-type{
  column-span: all;
  margin: auto;
  width: 50%;
}

Furthermore, to target the last item in a 2-column layout, if it's the only item in its row, I'm now using this:

p>img:nth-child(odd):last-of-type{
  column-span: all;
  margin: auto;
  width: 50%;
}

Solution

  • Your markup and css would help greatly. Without it though, you may be able to target a single element only by using:

    img:first-of-type:last-of-type { 
        /* centering styles */ 
    }
    

    Edit:

    After seeing the css, this becomes super tricky. I came up with this cringe-y hack:

    p>img:first-of-type:last-of-type {
      position: absolute;
      left: 50%;
      width: 50%;
      transform:translateX(-50%);
    }
    

    Which gets the job done...except that p element has no height afterward since nothing inside it is static. I don't see an obvious way to clearfix it either. Maybe someone can build on this idea?