15 ms·
Use spacer components instead of CSS margins (2020)
- 88913527 5y agoI mostly agree with this, but I would add a secondary construct on top of it. Sometimes you want collections of things to appear identical. You might want a component, that as part of its own public API, abstracts away the usage of the spacing component (author calls this "Stack"). Ex: suppose you have a list of images and you always want them to be 8px apart. So you package up the Stack and an <Image /> component, that takes an images[] array. This prevents the issue where engineers use the raw Stack+Image "atom" components and define random spacing rules: say the spec is 8, some engineers use 6, others 10, etc-- then you have inconsistent spacing in your app.
- peterangular 5y agoSo ban a huge part of the CSS box model. Got it... Margins are valid in many use-cases, specifically many people leverage them for typography. They can even still be valid with component-driven development as well.
- feupan 5y ago> So ban a huge part of the CSS box model. Yes, why not? While eliminating them is hard, the argument here makes perfect sense. We've all been fighting margins one way or another. One could even argue that negative margins are a symptom of the problem. When you use negative margins you're pulling the element out of the box and essentially causing overflow. Does this fix the issue sometimes? Sure. Is it the best option? Maybe it should just be the exception.
- peterangular 5y ago> We've all been fighting margins one way or another. Nope - not really. There's always been a huge distaste for the box model and it comes from a place of not understanding it vs. anything else. Margins + features like flexbox are a huge feature of modern web development. If I were interviewing a developer and they started to go off on "ban margins" it would cause the interview to go short. --- Since you bring up an edgecase to defend the article: negative margins. Negative margins are almost considered an edge-case use for my entire career which is as-old as the CSS spec. They would show up in situations where complex layouts were just not achievable (holy grail w/dynamic content width and static sidebars pre-flex/grid). The other place they would show up is simple "off-by-one" issues like placing a child div 1px over it's parent border in dropdowns etc. I'd say for the last 5-10 years specifically they've not been needed and are an artifact of legacy development before flex showed up. If I came across code using negative margins in a PR I'd ask the submitter to refactor. Idk - just saying that using an old edgecase as an argument against such a ubiquitous feature of the box model (which is core to FE development) seems off to me. --- One last thought - margins are still perfectly valid with components. It's just that component developers don't want to think about how their component may lay out with something else on the page. It's microservices fiefdom on the front-end calling to give up core web development features because people don't want to think about components interacting with others.
- janaagaard 5y agoA more accurate title for this blog post would be “Ban Outer CSS Margins from Components”.
- lelandfe 5y agoBingo. Author will be fighting an uphill battle on HN because of the lack of specificity (an appropriate problem for a CSS article)
- matsemann 5y agoOr people could just read the very short article instead of instantly assume stuff based on the title here.
- andy_ppp 5y agoGood luck with that…
- lelandfe 5y agoThe article's own title is "Margin considered harmful" and the body finishes with the sentence "Ban margin."
- tinus_hn 5y agoThe use of the ‘considered harmful’ trope should tell you al you need to know.
- laumars 5y agoI did read the article and frankly it’s little better than the HN title. It’s heavily biased, fails to offer a convincing argument to anyone other than those who already believed the title, and even explicitly says margins should be banned. Simply put, it’s not a good article.
- Veen 5y ago
- dreyfan 5y agommm, spacer elements. the new 1999 is looking pretty awesome.
- ncann 5y agoLet's use <br> for vertical separation, just like the good old days!
- speedgoose 5y agoLet's code all the apparence in the class attribute (instead of the style).
- diordiderot 5y agoWe do, its called tailwindcss lol (and its amazing)
- knowfilter 5y agoYou didn't get the memo? We moved the style attribute inside the class attribute now https://tailwindcss.com/docs/adding-custom-styles#arbitrary-properties https://tailwindcss.com/docs/adding-custom-styles#arbitrary-...
- diordiderot 5y agoDear God
- speedgoose 5y agoYes that was the joke (and I'm not a fan of it).
- cm-t 5y agoThat's so sarcastic, when you use proper <table>,<tr>,<td> in your html, you don't need <br> ⸮
- 5y ago
- archerx 5y ago
- vlrk_xero 5y ago
- vore 5y agoI think the main bugbear of margins that the article doesn't mention is margin collapse: I personally don't find the rules super intuitive and I would rather just be explicit with spacing than have the browser collapse things together!
- scns 5y agoOne way around this is to only define margins at the end of the container.
- bhk 5y agoBottom margins can still collapse with those of a parent container.
- jicea 5y agoAgree, collapsing margins are counterintuitive, and only applied to top and bottom margin. It’s really surprising how many people don’t know it’s a thing and fight the box model. If you think you’re constantly fighting layout, try to read the MDN docs [1] with a fresh eye. I was guilty to think I needn’t learn CSS, and reading the MDN really help me. [1] https://developer.mozilla.org/en-US/docs/Web/CSS https://developer.mozilla.org/en-US/docs/Web/CSS
- bhk 5y agoWhat's really surprising is how many people do know that margin collapse is a thing, but haven't fully understood all of the implications, so they still get mystified by some unintended consequence. I don't think that "go read all the MDN docs" is a very useful suggestion. More useful is something like the following, which I don't think you will find anywhere in MDN: When an element's top or bottom margin collapses with its parent, this may affect the position of the parent, because the minimum of the child and parent's margin will be used to position the parent. (MDN says the child element's margin will fall "outside the parent", but it is not clear that it will be used during layout to place the parent.) The bigger problem is that CSS is just so complicated and arbitrary. Consider the rule for collapsing margins with parents, from MDN: > If there is no border, padding, inline part, block formatting context created, or clearance to separate the margin-top of a block from the margin-top of one or more of its descendant blocks; or no border, padding, inline content, height, or min-height to separate the margin-bottom of a block from the margin-bottom of one or more of its descendant blocks, then those margins collapse. They list five different factors that prevent collapse, one of which ("block formatting context created") is a link to a page that defines it in terms of 15 different constructs or situations in CSS. On top of that, it appears that the MDN text is in error, because it lists intervening "height" as something that prevents bottom margin collapse, but not top margin collapse (when in fact it does).
- mvkel 5y agoMmmm nope. Margins and padding are hugely important for web usability and accessibility.
- locallost 5y agoThe point about not having it in a component is valid. It happens all the time that a margin on a component is different based on context. But there is no need to make it any more complicated than a margin -- just add the margin externally and if your framework can't do that, add a wrapper and put the margin there.
- madmod 5y agoMargin is generally more desirable than padding imo. Component/element knows the content it contains and uses margins to require a minimum amount of spacing. It avoids the need to make decisions on the spacing between every combination of components. Padding only works if you know everywhere your component might be used or don't mind remaking spacing decisions every time you use it. In my experience minimizing code needed for each use of a component leads to more coherently styled interfaces, particularly on larger or faster moving teams.
- deleted 5y ago[deleted]
- diordiderot 5y agoThe word padding isn't in the article... He reccomends spacing at the parent
- x3ro 5y agoThe author is arguing exactly that: remake spacing decisions every time you use a component, because that’s what many designers (most?) do. This is also true in my experience.
- HelloNurse 5y agoI want CSS to make spacing decisions so that I don't have to, and a system where graphical elements look good by default because they come with appropriate margins and containers adapt to what I want them to contain (e.g. by shrinkwrapping the content or by switching between different numbers of columns or rows) is more useful than a non-system that looks bad unless I keep many tedious ad-hoc specifications consistent. Moreover, > Margin breaks component encapsulation. A well-built component should not affect anything outside itself. Definitely not, margins are an essential part of a component, like a garden around a house, and they make components "usable in any context or layout" (unless the context or layout is stupidly overcomplicated).
- ui4jd73bdj 5y ago
- lykahb 5y agoFlutter does this, and its layout model is quite well thought.
- sgt 5y agoMy thoughts too. Building UI's in Flutter is a delight, as opposed to web technologies which can be a nightmare.
- wruza 5y agoIf it’s still built on canvas, doesn’t that mean something about the state of web layout.
- sgt 5y agoThat's true. That being said, Flutter Web is not entirely ideal and although it has some good use cases (very simple forms and web apps that need to be developed quickly), I would primarily suggest Flutter on iOS and Android.
- TimTheTinker 5y agoI understand and agree with the sentiment expressed here regarding the outer layout of components in a page (though I'd actually recommend using `gap` with a flex or grid layout). But margins can be incredibly helpful when implementing internals of complex components, and when laying out components next to each other that are not equal peers (like labels with form fields). Negative margins can also be very helpful in some circumstances, like when a border shouldn't contribute to the space taken by a component, or when components should overlap without resorting to absolute or relative positioning.
- avereveard 5y ago"A programmer does CSS" Rules without margins are going to be a mess. For one you can't negative margin the padding out of the first titles in a section and other useful negative margin pulls. Without margin collapse, you're going to need to handle first and last paragraph so they don't have half margin from their container. Margins are respected across the elements hierarchy, which is especially useful if you're reusing components in react like systems; neither nested paddings nor grids aren't suitable do that.
- bromuro 5y agoThis is a great pattern. How does margins work in SwiftUI ?
- mdemare 5y agoNo margins in SwiftUI, spacers and stacks.
- lelandfe 5y agoNeeds (2020) in the title. Original discussion, 123 comments: https://news.ycombinator.com/item?id=22676442 https://news.ycombinator.com/item?id=22676442 Anyway, considered harmful articles considered harmful. There is a time and place for margins. Being thoughtful with them is a better approach than "banning margin from all components." Should I really ban the use of `margin-left: auto` when positioning my flexed elements? I don't think this article is actually advocating for that, but a novice reader may.
- HelloNurse 5y agoBeing thoughtful is a better approach than "considered harmful" clickbait in any situation. Regarding CSS margins, they are part of the box model even if certain stylesheets neglect them, and the only conflicts they can be involved in are easily solved (a rule for "container x" is more specific than a rule for "x" and can override margins, particularly with parent padding, in special cases) and they highlight genuine design defects: trying to use a component both with and without its "natural" margins (without adding appropriate classes or wrapping containers), trying to specify conflicting margins, trying to fit variable-sized content inside fixed-size containers by messing with the content's required margins, and so on.
- underwater 5y agoA margin is contextual, so a reusable component shouldn't have them. It's a shame that CSS doesn't allow the parent element to define how spacing around the child elements should work.
- necovek 5y agoI thought you could do that with eg. parent > * { ... } There might be things missing to achieve whatever result you desire, but CSS does allow a parent element to define how spacing (and any other styling) works for child elements.
- 5560675260 5y agoWe can do this now with flexbox and grid. Spacer component from the article can be implemented with https://developer.mozilla.org/en-US/docs/Web/CSS/gap https://developer.mozilla.org/en-US/docs/Web/CSS/gap
- atian 5y ago[flagged]
- youngtaff 5y agoI like the approach that Cube CSS takes (https://piccalil.li/blog/cube-css/#heading-composition https://piccalil.li/blog/cube-css/#heading-composition) where margins are considered part of the overall layout rather than at the component level
- rimliu 5y ago
- izhak 5y ago
- djrockstar1 5y agoThe text of the article contains an argument to avoid margins when creating reusable components, instead allowing the consumer of the component define its margins. There is no argument made against using margin properties.
- izhak 5y agoThen the title of the article is misleading and should be changed to avoid confusion
- detaro 5y agoor you could maybe read the article before looking at its source code for a gotcha?
- izhak 5y agoor may be we should continue looking for gotchas when it comes to clickbait misleading titles and finally get the message of "clickbait is wrong" across to at least some part of tech blogging community?
- djrockstar1 5y agoThing is, clickbait works, so people will continue doing it. All your "gotcha" showed was that it works. Look at all the people in this thread engaging with this post, not because of its content but because of its title. If a clickbait title will lead to higher engagement, why would an author not use it? The best way to combat clickbait is to not fall for it, not play into it, to either ignore the article, or to read the article and discuss or critique the content instead of bringing more attention(all press is good press) to the title.
- ungamedplayer 5y agoWhat I would like is for a mobile site to both increase text size and reflow its contents as I pinch to zoom in on the site. Is it too much to ask ?
- eurasiantiger 5y agoUse the browser text size controls instead.
- ungamed 5y agohow do you do this on mobile while browsing the site ? (and not jumping into chrome properties continually ?)
- wruza 5y agoIsn’t it by chance in a site menu (an icon left to the domain name where a reader mode is)? https://androidinsider-ru.cdn.ampproject.org/ii/w820/s/androidinsider.ru/wp-content/uploads/2019/10/nexus-6-chrome-750x563.jpg https://androidinsider-ru.cdn.ampproject.org/ii/w820/s/andro... — a green one here? (this is a hot link)
- dusted 5y agoThere is an astonishing amount of css margin on that site. Edit: The amount of oscillation this comment has had (between -1 and +1) is amazing, I wish I could see total number of up and downvotes..
- onion2k 5y agoBan layout styling from your components entirely if you can. Make everything headless (eg https://headlessui.dev/ https://headlessui.dev/, https://www.radix-ui.com/ https://www.radix-ui.com/, plain old HTML, etc). Leave the way things look up to the app that uses them.
- wruza 5y agoWhat if a user needs it ready-to-use? Also imagine you’ve created some styleless form which I need to style according to my Bulma or Bootstrap stylesheet. What if the structure is different than these two are assuming?
- onion2k 5y agoI'm not suggesting the layout shouldn't be included at all. There's nothing wrong with including a default for the component - as a stylesheet in "examples" or something. The point is that layout shouldn't be a part of the component itself. The beauty of CSS is that it makes doing that absolutely trivial.
- baybal2 5y agoThe problem with CSS, and HTML is that content structure, content layout, and its styling is intertwined like spaghetti. A ground up HTML rewrite is needed.
- ryathal 5y agoThe problem is people treat HTML, CSS, and JavaScript like they are separate languages. They should be treated collectively like bytecode/binary and almost no one should need to know more than they exist, a compiler should be what's writing web output.
- the_other 5y agoAre you saying that content and layout _should_ always remain combined? I accept that we come to this understanding through our early introduction to language, writing and art. Most people intuitively link structure and presentation when they compose content. Separating them is incredibly useful. You can see this at a really basic level, in plain text. Lay out a single long paragraph of plain text into lines of max 80 chars, and then insert a word. The layout goes completely wrong and if you don't have tools to help you, you spend ridiculous amounts of time realigning the text. The line-length algorithm you're following (or using) is __totally__ separate from the content. HTML and CSS are this, scaled up to allow fine grained annotation and control of both semantics and presentation, independently.
- deleted 5y ago[deleted]
- deleted 5y ago[deleted]
- afrcnc 5y ago
- jyriand 5y agoWhy are there so many new component libraries with the same ideas and syntax? I thought the example was from chakra-ui but it was from Braid.
- AltruisticGapHN 5y agoThis is not a goods approach imho. When I'm the html/css guy on a team, it makes my work super frustrating to have to deal with devs who preemptively try to break down everything into smaller bits. It gets in the way of iteratively improving my templates and css throughout a project. The solution is simple. First, you should use the "bottom margins only" approach wherever possible, cf. CSS best practice "use single directions margins only". https://csswizardry.com/2012/06/single-direction-margin-declarations/ https://csswizardry.com/2012/06/single-direction-margin-decl... If the Vue/React devs I worked this even understood just this, and put single direction margins in their components, there would be less issues already with collapsed margins and/or unintended vertical spacings. Even better, just get rid of the spacing margins in the component altogether as the article suggest. But instead of creating more abstraction with "spacer" components, you simply add tailwind-style classes on your components such as list items, in the PARENT component's template. Then the html/css guy till has full control over the templating, it's fluid and simple to edit, and there is no headaches with abstract "spacer" components that also add unnecessary complexity and indentation in the templates. The main issue with "spacer" components is that in the end, the design is never this regular, There are always exceptions to the rule, and they are much more easily handled as I said by using atomic css classes like tailwind's `mb-*` in the PARENT template of the components you want to "space". In my experience this approach accounts for ALL scenarios I've run into in a simple elegant way. The PARENT component of those you want to space can always have a bit of logic in React/Vue for those cases where the spacings differ from the default in the app.
- thinkindie 5y agoam I the only one that think that the proposed solutions feels like late '90s/early 2000s with table layouts?
- dsego 5y agowhat's wrong with that? don't grid and flexbox feel like that as well?
- xialvjun 5y agoFlutter does it.
- fleddr 5y agoI fully agree with the solution. Spacer components are a sound concept if you consider that a component should have no awareness of the larger context it is placed in. A next step to make components even more robust is for them to respond to available space in the parent container (container queries). A spacer component is easy to understand and makes consistent spacing easy. There's nothing dirty or impure about it. You just mark it aria-hidden so that both search engines and screen readers ignore them. Another tactic is to apply component margin spacing on individual instances of a component, as a utility class. It will work most of the time, but is more fragile. There is but one issue: the internal padding of a component (which is perfectly normal to have) is visually experienced as a margin when two subsequent components share the same background color. In this scenario you're still theoretically consistent with your margins but visually it is not perceived as such.
- 7sidedmarble 5y agoYou didn't read the article either huh
- fleddr 5y agoI did. What do you mean?
- tristanperry 5y agoI do agree generally, but it's funny that the suggested solution (spacers) are basically back to the old 1px transparent gif trick from the 90s/early 00s. Nothing wrong with the suggestion, but it's just ironic that we seem to be coming full circle again. Next we'll probably have posts extolling <Table> components for layouts ;)
- lwhi 5y ago
- ratww 5y ago> I do agree generally, but it's funny that the suggested solution (spacers) are basically back to the old 1px transparent gif trick from the 90s/early 00s. They aren't the same thing. Check the link in the article [1]. It is using regular CSS, and some of those components use more modern things like Grids. They also aren't applied between components like old element-spacers. Component Spacers have much more in common with regular margin/padding than with 90s spacers. [1] https://seek-oss.github.io/braid-design-system/components/Stack/ https://seek-oss.github.io/braid-design-system/components/St...
- j0ej0ej0e 5y agoMy company recently had a FE candidate supply a test using tables.
- dmix 5y agoThere’s still a place for tables in some use cases. But that use case is thin.
- Mezzie 5y agocries in email
- MarcellusDrum 5y agoSerious question: What is inherently wrong with using Tables for organizing simple layouts? Is it frowned upon just because it is a "hacky" way of doing stuff?
- lwhi 5y agoMargins are part of the specification of CSS. Banning them would be crazy. If you don't like thinking about them, sure .. introduce the concept of spacer elements in your framework. But outlawing something because you don't fully understand its purpose isn't the way to go.
- ratww 5y agoI would recommend reading the article, or at least the top comments here. This is not what the article is advocating.
- lwhi 5y ago> We should ban margin from our components. Hear me out. Maybe the first line of the article? The implementation of the CSS spec is closely optimised for performance by the browser. Trying to achieve the same outcome by using other means, might feel like a clever way of conceptualising .. but I'd argue there's absolutely no need.
- ebingdom 5y ago> because you don't fully understand its purpose How did you arrive at the conclusion that OP doesn't understand margins?
- lwhi 5y agoBecause the author has gone to such lengths to avoid them! Creating extra markup specifically for presentation for example ..
- 734129837261 5y agoFor stand-alone components? Sure, that's good practice. But if you have a `section` with a `h3` inside of it, there's nothing wrong with using `margin-bottom: 1rem;` for that `h3` element. It's the best practice because it leads to less confusion that way.
- progx 5y agoSomebody invented grid before.
- littlecranky67 5y agoBeing a FE Developer myself I say there is no such thing as a standalone/full-encapsulated component in the FE world. Any non-trivial component always relies on, or uses outer contexts or side-effects. This could be non-scoped css stylings, translations, browser-environment specific state, global JS code/state, or networking state.
- the_other 5y ago"Banning margin" is excessive and clickbait-y. The Spacer components idea is fine. Using Grid or flex layout in spacers is very sensible. But you could also use margins. ``` .spacer-stack * + * { margin-top: 1em; } ```
- 7sidedmarble 5y agoThat's... what the article said. He's not saying don't use margin for anything, he's saying avoid giving your components margin. The Spacer component is literally just the CSS you posted.
- the_other 5y agoThere's something like 5 instances of clear rejection of the use of margins in the article and zero mentions of practical margin-based layout strategies. I stand by my assertion that the article is badly worded.
- bartaxyz 5y agoThere's a use-case for more than a single approach. Margins and also collapsible margins are tremendously useful. In case of text of an article for example, where space changes based on other elements on the page (e. g. larger space above headings - the linked article also uses them). In addition, if there's also CSS for `:first-child` that removes the leading margin and `:last-child` that removes the trailing, you can easily wrap them inside another component to remove the margins (or introduce a property to collapse them if you prefer). Of course, this is a bit more advanced and needs to be included in the documentation.
- roman-holovin 5y agoThat's very reductionist approach. Sure, margin is a sharp tool and you need to use it responsibly. I avoid putting margins on "first"-level selector. So instead of .button { margin-left: 16px } I do .parent > .button { margin-left: 16px } Difference is that I can reuse '.button' elsewhere without modifications. Another point to consider is that margin is not the only CSS property that affects layout. Both grid, flexbox and 'position' properties should be used with same care. And approach I highlighted above is usually good enough. For margin specifically there is also a "owl" selector that makes is a bit easier to manage .parent > * + * { margin-top: 16px; // OR margin-left: 16px; }
- goldenkey 5y agoI hadn't heard of the owl selector for selecting :not(:first-child). Thank you for teaching me something new!
- Kavelach 5y agoNote that the owl selector is pretty slow when it comes to being processed by browsers. If you use it sparingly, it shouldn't be so bad, but leave it all over the place, and you'll see the impact
- goldenkey 5y agoIs there a place to see css benchmarks on modern browsers, like jsperf used to be for JS? It seems like > *+*, *:not(first-child), *:nth-child(1+n) and *:last-child { ...revert... } are all equivalent. I would be curious to know which is most efficient.
- y4mi 5y agoHa, when I first learned about it I remade a pretty interesting navigation menu purely with :not :checked :focused :hover etc, so pure html and css, thinking it would be more performant then my previous JS version. Its performance was not just measurably worse, it was obvious as soon as I opened the revision on my phone. Lesson learned: it's important to think twice before using most pseudo selectors
- lewisl9029 5y agoAgreed with avoiding margins, especially on reusable components, as they remove a degree of freedom for how they can be laid out by users. But these days, instead of margins or spacer components, I would recommend just using flex gap and grid gap across the board. The difference being spacer components (and margins for that matter) don't wrap well, which is important for building fluid layouts that don't depend on hard-coded breakpoints. I find that parent components specifying a gap between their children also happens to align much better with my mental model for designing layouts, not so much with spacer components or margins. TL;DR: I haven't found any situation so far where I needed to reach for margins or spacer components ever since flex gap became widely supported. They're both dead to me now. Long live the gap.
- csbartus 5y agoSame approach over here.
- richeyryan 5y agoAbsolutely agree, the developments in flex and grid have done wonders for reusable components.
- rendall 5y agoThis article is but one example of why I think React is actively harmful to the web. Its practitioners generally speaking have little interest or incentive to understand what's going on under the hood, and it shows. Its compiled code, except with exceptional teams, has no semantics and baffling, sloppy css. The article's main point is a definitely worthy, arguable one: a React component perhaps should be entirely encapsulated, not affecting anything outside itself. Worth discussing, anyway. The solution is sadly typical, though. Just grab another component! No interest in what `<Stack>` is actually doing? How does it solve the problem? Does it use CSS? A single line in the style sheet: `display: flex` or `padding-bottom: 1rem` or something else like that? This cultural lack of interest is why we have website source code littered with nonsense like `<div class="h1">` and `<div style="position:absolute;">`
- armandososa 5y agoIn a nutshell: .stack > * + * { margin-top: 1rem; }
- rendall 5y agoLiteral laugh out loud. Thanks for that.
- deleted 5y ago[deleted]
- roman-holovin 5y agoI don't think it is fair to blame the tool for the mistakes of the operator. I feel like the real issue is that demand for software developers and specifically web developers is higher than than supply. Which leads to a situation where anyone who can put pixels on the screen, with at least some degree of reliability, will be hired and will put pixels on the screen. And they will choose whatever tool there is. Another issue is that if look through job postings carefully, you will see the pattern there where framework knoweledge is valued above everything else. It is "React Frontend Developer" or "Vue Frontend Developer", not just "Frontend developer who is capable to pickup whatever technology we use". There are reasons for that, of course, but it is hard not to see that this approach will likely skew hiring into looking for a specific knowledge in candidates. And candidates are going along with a path of the least resistance and learning stuff they need to work with backwards.
- lloydatkinson 5y ago> For example, the Braid design system popularized the Stack component: False, the Stack/Grid style component has been a maintstay of XAML based layouts for over a decade now, and at least generally speaking two decades old. Also, many web frameworks have had this for a while. Braid was not the first one. It's still a very well made framework though but the technical inaccuracy masks a whole load of history.
- andrewingram 5y agoI think "spacer components" is a bit confusing and not really the message someone should take away from this. I think it's better to say something like "Make parent components responsible for managing spacing around their children", not as catchy I admit.
- davidhariri 5y agoWhy not padding, then?
- justsomeuser 5y agoI use <br> to get a “one line height sized” spacer all the time.
- au-arms 5y agoClever, but this smells like a performance anti-pattern. Adopting this means you could, at worst, add 4 spacer divs per component. While most sites may never really feel a sting, for complex apps where reusability is a larger concern you've doubled to quadrupled the size of an already large DOM and you will be hit a death-by-one-thousand-cuts situation. Now you've got more... - html over the wire - html to parse for first render - DOM nodes to mount/unmount - memory usage from excess DOM - costly layouts due to extra nodes - lighthouse complaints of an excessively large DOM Otherwise a clean approach. Perhaps it could be solved at compile time or some other jsx -> CSS abstraction to maintain DX.
- thomasahle 5y agoCan't you just use the spacing properties of the container? Like flexbox's space-around and space- between?
- au-arms 5y agoYou can, however the lack of constraints on the spacing can make it difficult to match strict design systems. The dependence the spacing creates on the parent & child dimensions can lead to undesirable edge cases as well for dynamic/responsive content.
- kylemh 5y agoThe opposite would be the intent and the goal. Align design system language WITH your spacer components ensuring strict adherence. Layout components work and they don't have performance issues.
- au-arms 5y agoI think we agree here. The argument I am making is that spacer components that introduce DOM bloat can negatively impact large apps, especially on low power devices. A layout component does not have to introduce DOM bloat, it could apply layout directly via CSS to it's children. Layout components in this regard are incredibly helpful.
- spankalee 5y agoNot that I entirely disagree that the parent component should be able to override margins and position, but I think spacer components abstract this a bit too far, and really isn't necessary at all if you can just use CSS. This is probably due to an avoidance of exposing HTML and CSS to developers in React. Ideally the parent component would just have some styles that only effect the children, so you add this CSS to the parent: x-item { margin: var(--space-3) 0 0 0; } This works fine for custom elements (web components), but I think the problem is that in React you don't know what element a component is going to render, so it's generally much more difficult to target children this way.
- the_other 5y ago> This works fine for custom elements (web components), but I think the problem is that in React you don't know what element a component is going to render, so it's generally much more difficult to target children this way. This is exactly the problem "spacer components" solve.
- FloNeu 5y agoI strongly disagree... That breaks the separation of markup and styling - and requires the markup being adapted for different styling. Pretty dumb solution for a non-existing problem... I don't even understand we you think (outer)margins are part of a component... Just don't but it into a components style if it isn't required or wanted ... That I may agree. But you realize you can add margins in a parent layout - like the page-layout and add and manipulate for the child components this way? Another of this considered harmful articles that need the byline - if you don't really know what you're doing and/or talking about...
- iLoveOncall 5y agoHum, just use `box-sizing: border-box` and you solve the problem that the author has without using a complete anti-pattern.
- kylemh 5y agoNo, it doesn't. Margin may not affect the width and height of the element with `box-sizing: border-box`, but margin still breaks encapsulation and reusability of the component. You make layout assumptions by applying margin to a component.
- felipeccastro 5y agoI haven't tried it yet, but this article reminds me of a CSS-only library with hstack and vstack elements: https://almonk.github.io/pylon/ https://almonk.github.io/pylon/
- wildpeaks 5y agoI'd strongly advise learning what modern CSS can do thanks to grid, flex, column-count, gap, and rem units before bloating DOM tree diffs with empty div tags.
- nrbernard 5y agoExactly. It seems like the conclusion of the post should really be: don't apply layout styles to elements if their parent elements are responsible for layout.
- the_other 5y agoThe author could have called them "layout components" and the whole thing would have made a lot more sense.
- tsujp 5y agoPolluting the DOM with spacer components (which are going to be styled with CSS anyway) as opposed to using grid, or flexbox, or just margins themselves (no float layouts please) is wasteful and needlessly complex.
- darepublic 5y agoI have also started using spacers more often, and applying margin much more sparingly. Flex with gap is also another margin alternative. Dunno about larger dom concerns; a handful of extra divs doesn't seem like a big performance concern to me
- karaterobot 5y agoThis article acts like it's been a real challenge to get margins to work for the last 25 years. I have not had that experience. This seems like a solution in search of a problem, and likely a source of new problems down the road.
- movengeance 5y agoI think it's the language used that makes this sounds suspect. "Use layout components to control spacing" would be more clear about what the author is saying
- einpoklum 5y ago> Margin breaks component encapsulation. A well-built component should not affect anything outside itself. I guess I should make all my programs stop printing anything , and creating any files, because I wouldn't want them effecting anything outside themselves.