Search code examples
cssreactjsstyled-components

How to center items in a div without losing height of parent?


I have a container div with 2 spans inside it. When I try to align-items: center i lose the height and border-radius of the spans. I'd like them to retain their heights and border radius, while just being centered. How can I do this?

CSS of parent div:

const Container = styled.div`
  display: inline-flex;
  overflow: hidden;
  border-radius: 4px;
  margin: 0px 8px 10px 8px;
  height: 70px;
`;

CSS of child span:

const TextContainer = styled.span`
  padding: 8px 11px;
`;

Before align-items: center: enter image description here

After align-items: center: After align center


Solution

  • You can add display: flex to span and align items.

    .container {
      display: inline-flex;
      overflow: hidden;
      border-radius: 4px;
      margin: 0px 8px 10px 8px;
      height: 70px;
    }
    
    span {
      display: flex;
      padding: 8px 11px;
      background: #f00;
      align-items: center;
    }
    <div class="container">
      <span>Match Rank</span>
      <span>
      <img src="https://i.picsum.photos/id/83/60/50.jpg" />
      </span>
    </div>