Remove start and end margins with the margin-trim property

A frequently asked multiple-column layout question is why a new paragraph at the start of the column has additional space above it.

Text arranged into three columns, there is a margin applied to the top of the first column which means the start edge of the three columns doesn't line up.
The space above the first column is the top margin of the initial paragraph.

The space is the margin on the paragraph, which doesn’t collapse if the paragraph is inside a multicol container. The only fix is to not use a top margin on paragraphs.

However, the new margin-trim CSS property solves this problem. From Chrome 155 applying margin-trim: block-start to the multicol container will trim the margin on any element at the start of the container. You can see it working in this CodePen demo, using Chrome 155.

Text in three columns with a trimmed margin so the columns line up at the top.
The columns with margin-trim: block-start applied to the multicol container.

Safari has supported the margin-trim property on block elements since Safari 16.4, however it doesn’t support the property for multicol. Due to this partial implementation using feature queries to test support for margin-trim in multicol isn’t possible. In the linked CodePen, I use feature queries to test for margin-trim: block-start, and show a message to alert the viewer if their browser doesn’t have support. While Safari won’t show that message, the trimming of the top margin fails due to lack of support in multicol.

There are lots of useful applications for margin-trim in block layout. You can see some of these in the WebKit post Easier layout with margin-trim. I’m hopeful we’ll see this implemented everywhere for multicol soon, and I’ll finally have a good answer to one of the questions I get asked about multicol!

Leave a Reply

Your email address will not be published. Required fields are marked *

To respond on your own website, enter the URL of your response which should contain a link to this post's permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post's URL again. (Find out more about Webmentions.)