Home > Back-end >  why spacing between elements is different when data is changed in angular
why spacing between elements is different when data is changed in angular

Time:11-20

In my angular application, I am facing an issue, when I change data to a large list (some css is also changed), the space between elements becomes less.

I have made a small example of the issue with similar condition

stackblitz example - here

Try adding more contents to items array - more than 8, you will see change in bottom margin on elements.

Html -

<div class="container" [class.large-list]="items?.length > 8">
  <div *ngFor="let item of items" class="item">
    <p>{{ item }}</p>
  </div>
</div>

Css -

.container .item {
  display: inline-block;
  width: 20%;
  border: solid 1px red;
  margin: 20px;
}

.container.large-list .item{
  display: block;
  width: unset;
}

p {
  margin: 0;
}

Array in .ts file

  items = [
    'Some Item',
    'Some Item',
    'Some Item',
    'Some Item',
    'Some Item',
    'Some Item',
    'Some Item',
    'Some Item',
  ];

CodePudding user response:

Inline-block elements don't collapse their margins - see this Q:

Margin collapse on inline-block elements?

So in the first case the items are surrounded by an individual 20px margin which makes 40px distance to the item below as the margins don't 'merge' (collapse)

In the second case (large-item) the margins do collapse as the items are now display:block - so a 20px gap

The answer seems to be you'll need to make the margin-bottom: 40px for the large-item css rule, or find a layout that replaces inline-block (flex?)

  • Related