skip to Main Content

I’m struggling trying set the width to component in Angular. I’m using flex, maybe grid will help me with it, but i want to use flexbox to learn. Just to simplify, I have a page with a div that contains 6 instances of my component.

<main>
  <div class="card">
    <app-component [label]="1"></app-component>
    <app-component [label]="1"></app-component>
    <app-component [label]="1"></app-component>
    <app-component [label]="1"></app-component>
    <app-component [label]="1"></app-component>
    <app-component [label]="1"></app-component>
  </div>
</main>

the styles

.card {
    width: 600px;
    display: flex;
    flex-wrap: wrap;
}

The component:

<div class="row__input a">{{ label }}</div>

the component styles:

.row__input {
    display: flex;
    flex-direction: column;
    gap: 4px;
    max-width: 240px;
    width: 100%;
}
.a {
    height: 48px;
    background-color: red;
    max-width: 240px;
    width: 100%;
}

The problem is that i want to display the component with 240px as max-width so in case of full screen the fields are displayed with 240px widht, but as soon as i make screen smaler the component width should be smaler too.

One of the solutions that i found is the use of :host{ display:contents} but I’m not sure if it’s a good practice. Maybe it’s something related to the tag that angular use to place the component in DOM, because using directly the divs instead of the component, the widths are shown correctly.

Im sure that something is missing but i dont know what it is.
Also, do you think that mix grid and flexbox is a good practice?

Example project: https://stackblitz.com/edit/stackblitz-starters-4s35dh?file=src%2Fcomponent%2Fcomponent.scss

2

Answers


  1.     I think below css will do the job
        
        .card {
            max-width: 600px; // remove width or change to max-width: 600px;
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
        }
        
        Replace your component styles with
        
        :host {
            background: red;
            flex-basis: 240px; // sets base width
            flex-grow: 0; // sets max-width 240
            flex-shrink: 1; // allows shrinking
            display: flex;
            flex-direction: column;
            gap: 4px;
        }
    
    
    Login or Signup to reply.
  2. Updated project link which has equal width distribution among components => https://stackblitz.com/edit/stackblitz-starters-dxg2zf?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.scss,src%2Fcomponent%2Fcomponent.scss,src%2Fcomponent%2Fcomponent.html

    Added extra class ele on each component and then equally allocated space for each component by below flex-basis(100/ 6 = 16.66%)

       .ele {
          flex-basis: 16.66%;
          max-width: 240px;
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search