Mr Robot Mr Robot - 2 months ago 9
CSS Question

giving same widths on stacked flex elements

I am trying to position elements, an

img
and
div
, side by side which then stack on top of each other when the browser width becomes smaller to make it responsive.

I have managed to do this to a degree however I am unable to get the 2 elements to be the same widths when they are stacked on top of each other.

Also I am having trouble vertically aligning the text in the div to be in the middle instead of the top.

This is what I am trying to achieve.

enter image description here

JSfiddle https://jsfiddle.net/31c5vLn6/

Code:

.upperSection{
display:flex;
justify-content: center;
flex-wrap: wrap;
}
.upperBox{
background-color:white;
text-align: center;
verticle-align:middle;
}
.description{
background-color: white;
}


<div class="upperSection">
<img src="https://picturethismaths.files.wordpress.com/2016/03/fig6bigforblog.png?w=419&h=364">
<div class="upperBox">
<div class="description">
<span class="header"><br>Header</span>
<br><br>
<span class="text">Text Goes here</span>
</div>
</div>
</div>

Answer

.upperSection {
  display: flex;
  justify-content: center;
}
.upperBox {
  display: flex;                     /* 1 */
  text-align: center;
  background-color: white;
  
}
.description {
  display: flex;
  flex-direction: column;
  justify-content: center;
  flex: 1;                            /* 2 */
  background-color: white;
}
@media (max-width: 500px) {
  .upperSection { flex-wrap: wrap; }
  .upperBox { width: 100%; }          /* 3 */
}
<div class="upperSection">
  <img src="https://picturethismaths.files.wordpress.com/2016/03/fig6bigforblog.png?w=419&h=364">
  <div class="upperBox">
    <div class="description">
      <span class="header">Header</span>
      <span class="text">Text Goes here</span>
    </div>
  </div>
</div>

jsFiddle

Notes:

  1. By making this element a flex container, you're applying align-items: stretch to the child. This gives .description the height of the container, and justify-content then has space to work.
  2. Similar to #1, this gives the element full width, giving text-align: center space to work.
  3. Since the parent is a row-direction flex container, flex: 1 would work here, as well.
Comments