CSS gap is NOT a replacement for margins

  Рет қаралды 36,842

Kevin Powell

Kevin Powell

Күн бұрын

I’ve seen some people completely abandoning margins and turning to using gap for everything, and to me, that’s problematic. Don’t get me wrong, gap is an absolute lifesaver, especially when it comes to spacing out components. What it’s not best for, however, is spacing out regular flow content like text.
So, this isn’t to say that you should never use gap; it’s simply to say, use it for what it’s good at.
🔗 Links
✅ How I decide between using Flexbox and Grid: • Flexbox or grid - How ...
⌚ Timestamps
00:00 - Introduction
00:31 - Using gap to replace margin
02:12 - The problem with consistent spacing and the advantage of margins
03:45 - The places where gap is a life-saver
04:45 - The problem with using gap within components
06:40 - Removing margins in specific places is often easier anyway
07:56 - More good use cases for gap
#css
--
Come hang out with other dev's in my Discord Community
💬 / discord
Keep up to date with everything I'm up to
✉ www.kevinpowell.co/newsletter
Come hang out with me live every Monday on Twitch!
📺 / kevinpowellcss
---
Help support my channel
👨‍🎓 Get a course: www.kevinpowell.co/courses
👕 Buy a shirt: teespring.com/stores/making-t...
💖 Support me on Patreon: / kevinpowell
---
My editor: VS Code - code.visualstudio.com/
---
I'm on some other places on the internet too!
If you'd like a behind the scenes and previews of what's coming up on my KZbin channel, make sure to follow me on Instagram and Twitter.
Twitter: / kevinjpowell
Codepen: codepen.io/kevinpowell/
Github: github.com/kevin-powell
---
And whatever you do, don't forget to keep on making your corner of the internet just a little bit more awesome!

Пікірлер: 81
@Lundito
@Lundito Жыл бұрын
Definitely guilty of using gap more than I should! I'm actually in the process of reviewing the spacing on one of my projects and your video, with perfect timing as always, show up on my feed covering exactly what I was thinking about. :)
@PicSta
@PicSta Жыл бұрын
Visual hierarchy is the key for good designs and this means not also different font weights, colors and so on, it's also important to have different spacing. Section spacing, article spacing, headline, and paragraph spacing. And with spacing we tell visually what belongs together or separate it because it's new content.
@gatogordo4131
@gatogordo4131 Жыл бұрын
This video came in a good time, I was using gap for everything since I started learning css in depth last week.
@BuIIetBiII
@BuIIetBiII Жыл бұрын
For such a long time I didn't use gap at all and was really struggling with aligning cards together with margins. I didn't realise that you can use it for flex as well as grid. Lifesaver
@li_tsz_fung
@li_tsz_fung Жыл бұрын
until someone using iOS 14 or something complaints.
@bravefastrabbit770
@bravefastrabbit770 Жыл бұрын
@@li_tsz_fung jailbroken 13.3 here, I’ve just accepted my fate
@li_tsz_fung
@li_tsz_fung Жыл бұрын
@@bravefastrabbit770 few weeks ago, our clients complaint about their website being completely broken on their iPads. Turns out it's running iOS 12. And they thought it's iOS 16 just by looking at the system update page and it says 16 there.
@li_tsz_fung
@li_tsz_fung Жыл бұрын
@@bravefastrabbit770 I just don't understand why apple can't separate safari from system updates
@lukas.webdev
@lukas.webdev Жыл бұрын
Great video! Very helpful - thanks for sharing. 😉🔥
@GR_BackingTracks
@GR_BackingTracks Жыл бұрын
I'm building the grid of a framework for class right now, and this is TIMELY to say the least... Thanks, KP!
@blackpurple9163
@blackpurple9163 Жыл бұрын
Nice way to differentiate between both
@ShaharHarshuv
@ShaharHarshuv Жыл бұрын
Margins were designed for typography which was what html was originally about. As web dev we usually use html for UI, in which flex more make since almost always.
@fave1201
@fave1201 Жыл бұрын
Fair enough. I hadn't thought of the first example. I would probably have had containers for related content and had multiple gaps. Thank you.
@dealloc
@dealloc Жыл бұрын
The problem with margins is that they assume the context those elements are used in, which in turn makes it very easy to write too specific CSS classes which in turn often leads to duplicate CSS and become hard to maintain. This is especially noticeable in component libraries or component-driven architecture. Since moving to just flex/grid and gap for most of the components I build, which are often compound, sharing state, and composed together, I have never had a case with spacing issues. Growing and maintaining those components as requirements has changed over time has also been a breeze. This was not the case when I used margins (and even paddings, which creates a whole other set of problems).
@patricknelson
@patricknelson 5 ай бұрын
FWIW: I feel like in component architectures, the case for margins can be made _as long as_ they stay contained within the component that uses it. Problems seem to arise once those margins bleed outside of the element using those margins (for the reasons you’ve described).
@GrantAmbrose
@GrantAmbrose 11 ай бұрын
Great video Kevin. The line-heights of headings make the spacing not match when using gap and this was a reminder to not force it. Margins is easier in a lot of cases
@fadehelix
@fadehelix Жыл бұрын
I love your videos like this one because I can learn how to not overthink CSS and how to write a lot less code
@Dorchwoods
@Dorchwoods Жыл бұрын
We recently created a stack component in our company design system that literally just handles spacing between elements using gap. Its a web component so it works well in any framework. I really like that i can control the spacing directly from the HTML template and can minimize having to use a class with flex or grid just to add a gap. Now its just Or So handy!
@MaxWeir
@MaxWeir Жыл бұрын
Really like the grid-tempalte-columns rule, that handles everything all in one line!
@rickardelimaa
@rickardelimaa Жыл бұрын
I really don't like margins, and that's because of margin collapse and how margin doesn't affect box model (which it shouldn't). So I use padding as much as I can. It's really an exception when I use margin, usually only for vertical space between sections.
@andrillaf
@andrillaf Жыл бұрын
I love this! Thank you!
@StarOnCheek
@StarOnCheek Жыл бұрын
I feel like HTML accidentally evolved into having 2 separate flows: the Document flow (original purpose) and th UI flow (most popular, mistakenly preferred over document flows a lot of times) and margins make by far most sense in the document flow which is why we see them less.
@leno-design
@leno-design Жыл бұрын
In today's component-driven world, I think it's best not to let the child decide how much space the parent should have. That's why I try to steer clear of using margins as much as possible. In the first example, we can get the same result by using "gap" and setting the padding just right. Thanks a lot, Kevin, for making these super helpful videos!
@dealloc
@dealloc Жыл бұрын
Indeed. Margin is harmful imo. Max Stoiber has a great blog post on the matter (just replace "Spacer components" with "gap")
@allsunday1485
@allsunday1485 Жыл бұрын
Dude lives in a completely different era
@patricknelson
@patricknelson 5 ай бұрын
@@allsunday1485Are you referring to Ken or Max Stoiber?
@DarkReaperK97
@DarkReaperK97 Жыл бұрын
I love gap! I use it all the time. I worked on a project just last week. A simple landing page and we didn't use margins at all!
@Cipscis
@Cipscis Жыл бұрын
Another pitfall of gap that I've run into, when I wanted to use consistent spacing between elements without extra space on the ends, is that hidden elements will still have a gap added for them. Whereas hidden elements won't have a margin. If elements are being added and removed from the DOM this isn't a problem, but it can come up sometimes if things are being hidden and shown on different screen sizes.
@patricknelson
@patricknelson 5 ай бұрын
I’m curious about this. For the pitfall with gap, what technique for hiding works better with margin that doesn’t work as well with gap? Is this “hidden” referring to techniques like “visibility: hidden” and “opacity: 0” or are they removed from flow like “display: none”? Or is it more of an HTML structure issue?
@patricknelson
@patricknelson 5 ай бұрын
Essentially, margin allows you to more easily set a hierarchy of spacing for adjacent siblings. *However* gap is super useful particularly in component architectures since I’ve found that margin has a tendency to bleed outside of the component which can cause issues (with styling best applied by the parent/owner element). That said, it’s still a case-by-case basis so not sure there’s a silver bullet there.
@ShaharHarshuv
@ShaharHarshuv Жыл бұрын
I don't agree with the over engineering that goes into avoiding 1-3 lines of codes. I prefer to write that extra few lines if I can think about it less. Plus, if you are worried of code duplication you can use either mixins or components.
@xarunoba3894
@xarunoba3894 Жыл бұрын
I've been using gap and padding 😅
@AndyGaskin
@AndyGaskin Жыл бұрын
good overview
@CharlesSmall
@CharlesSmall Жыл бұрын
Thank you Kevin.
@jfftck
@jfftck Жыл бұрын
The next area that CSS should focus on is having a preset property that would change the behavior of the page between document, app, etc… The fact that we have CSS resets is enough to justify it becoming a native feature. I am thinking that properties like margin having behavior that you have to take collapsing into consideration, it should have a way to disable it and allow margins to never collapse. But until that happens, it will always be a game of what popular method is everyone going to adopt to make web pages look the way we want them. It started with tables and we have finally made it to grid, but unfortunately only Firefox is taking sub grid as a needed addition and making grid really shine. I am tired of the hacks that have been used throughout, with the worst being the property names that contained characters that would be ignored by some browsers and target those that didn’t with override values (thankfully this trend has mostly disappeared).
@Killyspudful
@Killyspudful Жыл бұрын
Subgrid is coming in Chrome within a version or two and I believe it's now in Safari too.
@nomadshiba
@nomadshiba Жыл бұрын
the thing is css is made for articles and documents but these days we use it for building apps and apps usually dont have any articles and grids are perfect for apps because they are great for building layouts and apps are made out of layouts i would reset everything and use grids everywhere and i would have some class when used gives elements under it the default margins and paddings and stuff for articles also im a fan of using `em` instead of `rem` because after building everything with it, it lets me scale up and down things just by changing the `font-size` of the component root. want a bigger button? just make the font size 1.5em. also lets say i have a card, and card has a button, and i want button to be smaller relative to that card, i can set the button font-size to .9em and its smaller then lets say im using the card somewhere else, i can just make its font-size bigger and smaller to make it bigger or smaller and button is not gonna stay small when i make the card bigger and etc, everything sized relative to their parent.
@rossclutterbuck1060
@rossclutterbuck1060 Жыл бұрын
your use of em here is the exact purpose of rem. Use rems for everything inside your design and then set font-size in the html or ::root to define what an em should be for the relative ems to draw from.
@WPPatriot
@WPPatriot Жыл бұрын
@@rossclutterbuck1060 Only if you consider the size of elements only on a document level. If you'd want to resize everything in a certain component, you wouldn't be able to because it's all sized to the root font-size. That said, I dislike using em as well precisely because it's tied to the font size. I'd honestly prefer an arbitrary 'size' property that does nothing but dictate the size of em units.
@lawrencedoliveiro9104
@lawrencedoliveiro9104 Жыл бұрын
Yup, building apps (particularly intranet apps) is what I do, and I’ve been using grids a lot since I discovered them.
@pablowbk
@pablowbk Жыл бұрын
Huh, good call Kevin. Using em for the margin top is a good takeaway here
@karthicc6157
@karthicc6157 Жыл бұрын
Hi, My empty grid-item is taking extra space. how do i remove the gap of empty grid-items.
@mibi2007
@mibi2007 Жыл бұрын
I know that but I still use flex and gap because if I transfer the web to the mobile app it will be consistent, margin is not used in my mobile for some reason
@NotKyleChicago
@NotKyleChicago 18 күн бұрын
Is there a significant difference between margin-top and margin-block-start? It seems like you used both but I don't know what the difference is between them.
@marielemaitre5006
@marielemaitre5006 Жыл бұрын
And thank you again! Do you own a bird or was your window open on your garden? 😊
@roberthalbach1461
@roberthalbach1461 Жыл бұрын
Not really on the topic, but could you showcase PUG (former Jade)? I just discovered it recently and it's insanely good for templating static pages. It's quite aged right now but I feel that it's still so much more convenient than writing plain html. Would love to see it -- just as much as your other videos 💃
@najlepszyinformatyk1661
@najlepszyinformatyk1661 Жыл бұрын
really strange approach, neither of the popular frameworks use it, so it's not worth the time
@roberthalbach1461
@roberthalbach1461 Жыл бұрын
Disagree. I personally (and a lot of others) simply have no need for larger frameworks, yet the level of convenience delivered by pug makes me not want to miss it.
@nivoset
@nivoset Жыл бұрын
Had to check myself since i do like using gap. But then i dont do these types of layouts and generally are doing same spaced table things or the like. We do have a problem that safari only recently updated to allow gap in flex, so we do have old browsers used that do not. Hopefully fixed soon
@KevinPowell
@KevinPowell Жыл бұрын
Support for older versions of won't happen, we just have to wait as people get newer devices and are able to be on newer versions.
@user-km9vl9ck9u
@user-km9vl9ck9u Жыл бұрын
very nice!!
@poooooow
@poooooow Жыл бұрын
flex-direction: row (🧠: to make rows)
@user-ut5df7xs7v
@user-ut5df7xs7v Жыл бұрын
Justify-content can't be used in Grid Display?
@lukas.webdev
@lukas.webdev Жыл бұрын
justify-content is for flex and justify-item is for grid 😉
@shreyashsingh6195
@shreyashsingh6195 Жыл бұрын
Sectionalizing and adding padding to separate children elements is better than margin as a lot of times they overlap with other elements
@Gearyco
@Gearyco Жыл бұрын
Bad practice because padding alters your boxes.
@shreyashsingh6195
@shreyashsingh6195 Жыл бұрын
@@Gearyco I use box-sizing:border-box to account for padding. Should I not be doing that?
@Issvor
@Issvor Жыл бұрын
Ehh, the example of using margin top inside the cards instead of gap is a stretch. Gap+grid/flex is more developer friendly than combining pseudo selectors like not and first-child. Margin definitely has its place, but I also don't think that relying on gap is bad, especially if the argument is "you write less code with margin" when it maybe saves you a single line, and having to use the lobotomized owl
@soullighter
@soullighter Жыл бұрын
I love to use Gap in Flex, but i find out there is a bug on iOS devices. And after that I am skeptic. Someone here in comments say it is iOS 14
@wlockuz4467
@wlockuz4467 Жыл бұрын
What is the logical translation for the "* + *" selector?
@WPPatriot
@WPPatriot Жыл бұрын
It selects all elements that have a sibling-element before it. Here's a tip: Read your CSS selectors from right to left. So `article > * + *` is: Select any element (*) that has a sibling before it (+) that can be any element (* again) that are direct descendants (>) of article-elements (article). EDIT: Formatting changes
@wlockuz4467
@wlockuz4467 Жыл бұрын
@@WPPatriot Thanks! I know how to read selectors but this is the first time I've seen this one.
@lawrencedoliveiro9104
@lawrencedoliveiro9104 Жыл бұрын
It’s a question of operator precedence: comma has the lowest precedence, then space or ”>”, then “+” or “~”.
@moneyfr
@moneyfr Жыл бұрын
Gap is much better than tailwind space-x-4 for performance
@radvilardian740
@radvilardian740 Жыл бұрын
This is the reason why I prefer styling my projects with mobile view first, bcos sometimes we dont even need unnecessary styling at the first place. Always prefer mobile view first lads..
@AlThePal78
@AlThePal78 Жыл бұрын
This is a little confusing because I need to learn more css especially with grid and gap and no grid or flex and grid
@artemsapegin
@artemsapegin Жыл бұрын
Gap makes a lot more sense when you stop writing custom styles every time and start using primitive components like Stack. Nesting Stacks give you hierarchy in code and on the screen.
@jerondiovis6128
@jerondiovis6128 Жыл бұрын
Python has walrus operator. CSS has lobotomized owls. The entertaining zoology in web dev.
@7iomka
@7iomka Жыл бұрын
Safari < 14.5 🚫 supports gap with flex...
@a1white
@a1white Жыл бұрын
global resets are awful. I remember when I first started coding back in the day of IE6 and Internet explorer on a Mac we used global resets in a big way, because all the browsers had different box model interpretations. Nowadays with standards, this is not an issue. Natural margins and paddings are your friend. Don’t fight it.
@icinemagr4621
@icinemagr4621 Жыл бұрын
amazing
@c__beck
@c__beck Жыл бұрын
"We might be left writing a bunch of extra code just to get back to how things were before, which seems like a total waste of time." YES THIS! I've been saying this for _years_ but for some reason people like to do more work for the same outcome 🤷‍♂
@rossclutterbuck1060
@rossclutterbuck1060 Жыл бұрын
I will never understand the industry hardon for TypeScript and SASS. Just learn JavaScript and CSS properly in the first place and stop doubling up your workload with unnecessary cruft.
@dealloc
@dealloc Жыл бұрын
@@rossclutterbuck1060 The problem is not that people don't know how to use JS and CSS. There are good reasons why things like TypeScript are used in pretty much any serious project. They scale and are easier to maintain over long time. As for Sass/SCSS, it has its flaws when (mis)used to generate massive amounts of CSS for little gain.
@n8_may
@n8_may Жыл бұрын
(* + *) lobotomized owl. love it
@luiscolome75
@luiscolome75 Жыл бұрын
Exactly, GAP is made to separate columns, no to substitute margins! I would never use gap for that. Thanks anyway Kevin, as always it's nice to see your videos!
@yzz9833
@yzz9833 Жыл бұрын
Lol you still use CSS?
@lukas.webdev
@lukas.webdev Жыл бұрын
What are you using for styling? Tailwind? 🤔
@MrTomro
@MrTomro 11 ай бұрын
????
@reactivicky
@reactivicky Жыл бұрын
First comment 😊
@adamuk73
@adamuk73 Жыл бұрын
2st comment 😂
Avoid these 5 beginner CSS mistakes
21:38
Kevin Powell
Рет қаралды 70 М.
How to make a nice site with less CSS
18:56
Kevin Powell
Рет қаралды 55 М.
ИРИНА КАЙРАТОВНА - АЙДАХАР (БЕКА) [MV]
02:51
ГОСТ ENTERTAINMENT
Рет қаралды 3,1 МЛН
ТАМАЕВ vs ВЕНГАЛБИ. Самая Быстрая BMW M5 vs CLS 63
1:15:39
Асхаб Тамаев
Рет қаралды 4,8 МЛН
The 6 most important CSS concepts for beginners
28:58
Kevin Powell
Рет қаралды 150 М.
Collapsing margins - what they are and how to deal with them
14:31
Kevin Powell
Рет қаралды 64 М.
Extending Phoenix LiveView with Hooks
19:11
Code & Stuff
Рет қаралды 851
You might not need useEffect() ...
21:45
Academind
Рет қаралды 151 М.
Subgrid & Container Queries change how we can create layouts
21:08
Kevin Powell
Рет қаралды 72 М.
Two simple layouts that work better with Grid
14:05
Kevin Powell
Рет қаралды 59 М.
5 super useful CSS properties that don't get enough attention
16:23
Kevin Powell
Рет қаралды 141 М.
Getting started with CSS nesting
27:14
Kevin Powell
Рет қаралды 67 М.
Top 10 CSS One Liners That Will Blow Your Mind
13:34
developedbyed
Рет қаралды 910 М.
Write better CSS using logical properties
20:40
Kevin Powell
Рет қаралды 50 М.
ИРИНА КАЙРАТОВНА - АЙДАХАР (БЕКА) [MV]
02:51
ГОСТ ENTERTAINMENT
Рет қаралды 3,1 МЛН