Home > Software design >  Align divs next to each other in container and make container take width of children
Align divs next to each other in container and make container take width of children

Time:11-20

I want a container div:

  • Which should take width of its children.
  • I want its children to align horizontally.
  • And container should be single horizontal line

I don't want to use flex because then CSS tries to squeeze the children in containers width. This is solution I came up with which seems to work but I want to better understand the properties I used, hence the questions.

    import React from 'react';
    import './style.css';
    
    export default function App() {
      return (
        <div className="container">
          {[1, 2, 3, 4, 5, 6, 7, 8, 9].map((x) => {
            return <div className="card">{x}</div>;
          })}
        </div>
      );
    }

css

    .container {
      display: inline-block;
      background: red;
      white-space: nowrap;
    }
    
    .card {
      display: inline-block;
      width: 100px;
      height: 100px;
    }

  • My main question is: why do we need two inline-block usages? (one on the container one on the cards)
  • You can see I had to add white-space: nowrap; was it necessary in this situation?

Mainly I am interested in above questions, but if you additionally have a more elegant solution also, you can post it.

CodePudding user response:

display: inline, the major difference is that display: inline-block allows to set a width and height on the element.

Also, with display: inline-block, the top and bottom margins/paddings are respected, but with display: inline they are not.

CodePudding user response:

.container {
    display: inline-flex;
    background: red;
    // Add Gap between the cards 
    gap: 3rem
  }
  
  .card {
    flex: 0 1 100px; 
    max-width: 100px

  }
  • Related