Why can't I flex a container with a percentage width?

My page (added notes inside CSS to show you where the right container is)

Hey people,

I have a challenge I’m doing and these are my issues:

  • .star-card has a width of 80%, for some reason I cannot move this container to ‘flex-end’ as seen in the photo. However, changing the width from % to say rem, it does what I want. If I keep the %, the only thing to move to flex-end is the children of .star-card, why is this?

  • If I chose to use margin-left/right:auto to move nth-of-type(3) to the end, how would you set the middle container?

Thanks guys

If you want .star-card to be placed using flexbox it has to be a flex item. Right now it’s only a flex container (so it can move its own content using flexbox, but it can’t itself be moved). You have to make .star-card-container a flex container so its child elements (.star-card) can be moved using space distribution on the parent and/or self align on the children.

One possible option:
.star-card-container {
  width: 50%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  
  /* align all children horizentally in the center */
  align-items: center;
}

/* align first card to start */
.star-card:nth-of-type(1) {
  align-self: flex-start;
}

/* align last first card to end */
.star-card:nth-of-type(3) {
  align-self: flex-end;
}

Make the parent a flexbox container and use one of the distribution/alignment options for the content (flex items) to center them all (the auto margin on the first and last will still work). You can use the same code as posted above just with first and last child elements using auto margin instead of align-self.


Just as an aside you can’t just give all the .star-card bottom margin to create the gap between the elements, as that will push the last element away from its containing box. You can use top/bottom on the center, or not target the last element for the margin. For Chrome and Firefox, you can just use gap: 0.5rem on the flex container (check browser support).

1 Like

You made it sound so simple! Thank you, just what I’m looking for, thank you also for suggesting an answer for the margin too.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.