apdm apdm - 1 month ago 9
CSS Question

How can I display two divs inline while also centering them vertically using flex-box?

I have 2 divs inside another div container. I'm using flexbox to center them vertically inside the container, but I want them to be next to each other horizontally rather than one on top of the other. I tried a few different approaches including changing the

display
property of the container from
flex
to
inline-flex
as well as adding
display:inline-block
to the child divs. Here is a picture of what I'm working with. As you can see the 2 divs (the picture and group 1 label) are centered within the parent div, but I want Group 1 to be next to the picture instead of below it.

enter image description here

Code below and link to JSfiddle:

HTML

<div class="user-group">
<div>
Picture 1
</div>
<div class="user-group-name"><h4>Group 1</h4></div>
</div>


JS

.user-group{
font-family: 'Purista';
border: solid 1px;
display: inline-flex;
float: left;
justify-content:center;
align-content:center;
flex-direction:column; /* column | row */
width: 50%;
height: 200px;
}
.user-group > div{
display: inline-flex;
}

Answer

It depends if you intend to have multiple picture + text pairs in the element. If you don't, simply using align-items: center should fix your issue. There are some issues with your code:

  • align-content is not a flex property
  • Avoid using display: inline-flex, your situation does not call for it
  • Floats and flex are conflicting layout methods. Pick one—in this case, we settle for flex.
  • Use the default flex direction, which is row (if undeclared, it defaults to row, so we can just remove that property)

.user-group {
  font-family: 'Purista';
  border: 1px solid;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 50%;
  height: 200px;
}
h4 {
  margin: 0;
}
<div class="user-group">
  <div>
    <img src="https://placehold.it/32x32" alt="" title="" />
  </div>
  <div class="user-group-name">
    <h4>Group 1</h4></div>
</div>


On the other hand, if you have multiple picture + text pairs, you will have to resort to nesting. Each pair will have to be wrapped by an additional <div>:

.user-group {
  font-family: 'Purista';
  border: 1px solid;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  width: 50%;
  height: 200px;
}
.user-group > div {
  display: flex;
  margin-bottom: 10px;
  }
h4 {
  margin: 0;
}
<div class="user-group">
  <div>
    <img src="https://placehold.it/32x32" alt="" title="" />
    <div class="user-group-name"><h4>Group 1</h4></div>
  </div>
  <div>
    <img src="https://placehold.it/32x32" alt="" title="" />
    <div class="user-group-name"><h4>Group 2</h4></div>
  </div>
  <div>
    <img src="https://placehold.it/32x32" alt="" title="" />
    <div class="user-group-name"><h4>Group 3</h4></div>
  </div>
</div>

Comments