Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why spacing between elements is different when data is changed in angular

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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',
  ];

>Solution :

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?)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading