cfogelberg cfogelberg - 4 months ago 24
CSS Question

How to vertical center Bootstrap column contents that collapse to vertical on small screens

Short version:

I am using Bootstrap 3.3.7 and have a row where I need:


  • the columns to be horizontal, when the screen is wide enough

  • the column contents to be vertically centered when horizontal

  • the columns to stack vertically, when the screen is too narrow



The column heights aren't the same as each other or knowable in advance. How do I achieve my three goals?

Detail:

I have a visual component in my web page that has an image on the LHS and some text in media blocks on the RHS. The media blocks are taller than the image (exactly how much depends on the screen width and wrapping of the text).

We are using Bootstrap 3, so the basic HTML for this is:

<Row>
<Col md={6}>
<img src="myimage.jpg"/>
</Col>
<Col md={6}>
<div>a media block</div>
<div>another media block</div>
<div>etc</div>
</Col>
</Row>


So that the visual design looks clean and tidy I need to vertically centre the image on the LHS. To do this I've used flex boxes:

.eq-height-cols-wrapper: {
display: flex;
}

.eq-height-col: {
margin-top: auto;
margin-bottom: auto;
}

<Row class="eq-height-cols-wrapper">
<Col class="eq-height-col">
...


This seems to be the pretty standard solution for modern browsers (e.g.: 1, 2), but it means the columns don't stack at small screen width.

What can I do to vertically centre a column of unknown height relative to the other columns, also of unknown height, so that at small screen width it collapses and displays vertically?

Answer Source

Use a @media query to only apply on larger screens. Since the md breakpoint is 992px in Bootstrap, you'd use this. Flexbox is a good method for vertical centering.

@media (min-width: 992px) {
 .eq-height-cols-wrapper: {
  display: flex;
 }

 .eq-height-col: {
  margin-top: auto;
  margin-bottom: auto;
 }
}