Learn CSS BEM (and avoid these common mistakes)
Summary
TLDRThis video script delves into the intricacies of CSS methodologies, focusing on BEM (Block Element Modifier). It explains that CSS can be challenging due to its numerous components like selectors, box model, and flexbox. BEM offers a structured approach to writing maintainable CSS by organizing styles into blocks (reusable layout parts), elements (components within blocks), and modifiers (style variations). The script clarifies the use of naming conventions, avoiding high specificity, and common pitfalls like using margins on blocks. It also touches on the flexibility of BEM, such as blocks being elements or utility classes. The speaker encourages viewers to ask questions and shares a personal milestone of reaching 100 subscribers.
Takeaways
- 😀 CSS is challenging due to its vast knowledge requirements and potential for creating unsystematic 'Spaghetti code'.
- 🔧 CSS methodologies, like BEM, provide a structured approach to writing styles to maintain code quality.
- 🔑 BEM stands for Block, Element, Modifier, and helps in organizing CSS for better maintainability.
- 🧩 A Block in BEM is a standalone piece of the layout, which can be reused across different contexts.
- 📐 Elements are parts of a block that only make sense within the context of that block and do not function independently.
- 🎨 Modifiers in BEM represent variations in style or state of a block or element, avoiding high CSS specificity.
- 📄 When naming in BEM, focus on describing the layout rather than the content to ensure reusability.
- 🔄 Grid is a special block type that serves as a container for other blocks but cannot stand alone semantically.
- 🚫 Avoid using margins on blocks as it can hinder reusability and lead to maintenance issues.
- ❌ Common mistakes in BEM include nesting CSS classes, using BEM entities like utility classes, and creating overly complex or simple blocks.
- 🌟 The speaker emphasizes the importance of community engagement, answering questions, and the personal milestone of 8,100 subscribers.
Q & A
What does CSS methodology entail?
-CSS methodology refers to a set of rules that guide the writing of CSS styles to ensure systematic and maintainable code.
Why is BEM considered beneficial for CSS?
-BEM (Block, Element, Modifier) is beneficial because it helps avoid the 'Butterfly Effect' in CSS, where changes in one part of the project can cause unintended side effects elsewhere, making projects easier to maintain.
What is the significance of the double underscore and double dash in BEM syntax?
-The double underscore and double dash in BEM syntax are used to denote elements and modifiers, respectively, which helps in creating a clear and systematic naming convention for CSS classes.
What is a 'Block' in BEM and how is it different from a 'Grid'?
-A 'Block' in BEM is a standalone component of a layout that can be reused in different contexts. A 'Grid' is a special case of a block that cannot stand alone semantically but serves a functional purpose as a container for other blocks.
How should you name blocks in BEM to ensure reusability?
-Blocks should be named in a way that describes their layout rather than their content to ensure they can be reused in different contexts.
What defines an 'Element' in BEM?
-An 'Element' in BEM is a part of a block that does not have semantic meaning or function on its own and only makes sense within the context of its block.
Why is it recommended to keep CSS specificity low in BEM?
-Keeping CSS specificity low in BEM helps maintain a flat structure, avoiding nesting and concatenated selectors, which simplifies the CSS and makes it easier to maintain.
How do modifiers work in BEM and what is their purpose?
-Modifiers in BEM represent changes in state or slight visual modifications of a block or element. They are used to alter the style or behavior of a block or element without creating entirely new classes.
What is the difference between using a modifier and creating a new block in BEM?
-Modifiers should be used for minor changes to a block or element, such as color or size. If extensive changes are needed, creating a new block is recommended to avoid complex overrides and maintain clarity.
Can a block also be an element at the same time in BEM?
-Yes, a block can also be an element at the same time in BEM. This is common in patterns where one block is used as a component within another block.
What are some common mistakes to avoid when using BEM?
-Common mistakes to avoid in BEM include using margins on blocks, nesting classes in CSS, treating BEM entities like utility classes, creating elements of elements, and creating blocks that are either too complex or not reusable.
Outlines
📚 Introduction to CSS Methodologies and BEM
The paragraph begins with the speaker recounting their earlier statement about the complexity of CSS and the need to learn it quickly. They introduce CSS methodologies as a set of rules to follow when writing styles, with BEM (Block Element Modifier) being one of them. BEM's syntax, which includes double underscores and double dashes, may seem odd at first, but it becomes intuitive once understood. BEM is explained with the example of blocks, which are standalone parts of a layout, possibly reusable. Blocks can be semantic or functional, like a grid. The speaker emphasizes the importance of naming blocks based on their layout rather than their content for reusability. The paragraph concludes with a discussion on why the grid is considered a special case in BEM.
🔍 Deep Dive into Blocks and Elements in BEM
This paragraph delves deeper into the concept of elements within BEM. Elements are parts of a block that cannot stand alone; they lack semantic meaning and function only within the context of a block. The speaker uses a button with a label and icon as an example to illustrate the concept of elements. The paragraph also explains the CSS implementation of BEM, advocating for low specificity by avoiding nesting and using single class selectors. Modifiers, which represent changes in state or slight visual modifications, are introduced, with an example of how to apply them to both blocks and elements. The speaker provides tips on using modifiers and the decision-making process between using a modifier or creating a new block.
💡 Practical BEM Usage and Common Questions
The speaker addresses common questions and considerations when using BEM. They discuss the application of modifiers to elements, providing examples of how to highlight specific content. The paragraph also covers the decision of when to use a modifier versus creating a new block, emphasizing the importance of low specificity and avoiding extensive overrides. The speaker explains how blocks can be elements and even other blocks, providing examples and discussing the implications for reusability and maintainability. The paragraph concludes with a discussion on the use of utility classes within the BEM methodology.
🚩 Avoiding Common Mistakes in BEM
In this paragraph, the speaker outlines common mistakes to avoid when using BEM. They caution against using margins on blocks as it can hinder reusability and lead to maintenance issues. The paragraph also warns against nesting classes in CSS and using BEM entities like utility classes, which can increase specificity and go against BEM principles. The speaker advises against creating elements of elements and creating blocks with too many or too few elements, emphasizing the importance of abstraction and reusability. The paragraph concludes with a brief acknowledgment of the channel's milestone and an invitation for further questions from the audience.
🎉 Conclusion and Subscriber Milestone
The final paragraph is a conclusion where the speaker expresses gratitude for reaching 8,100 subscribers on their YouTube channel. They emphasize the personal significance of this milestone and their commitment to continue creating helpful content. The speaker thanks their audience and looks forward to the next video.
Mindmap
Keywords
💡CSS Methodology
💡BEM
💡Block
💡Element
💡Modifier
💡Specificity
💡Spaghetti Code
💡Semantic
💡Reusability
💡Utility Classes
💡Nesting
Highlights
CSS methodologies, like BEM, help create maintainable, systematic, and reusable code.
BEM stands for Block Element Modifier and is a methodology for structuring CSS classes.
Blocks are reusable parts of the layout, such as buttons, cards, and grids, which can function independently.
Elements exist within the context of blocks and don't have independent functionality, like labels or icons within a button.
Modifiers represent changes in state or visual alterations of blocks or elements, such as changing a button color from orange to green.
One of BEM’s core principles is to keep CSS specificity low by avoiding nesting and using flat class selectors.
Naming blocks based on layout rather than content helps make components reusable across different contexts.
Utility classes can be used with BEM, but it's important to remain consistent and use them in moderation.
Common mistake: adding margins to blocks, which affects reusability when blocks are used in different contexts.
Avoid nesting classes in CSS to maintain BEM's low specificity and flat structure.
Another common mistake is creating elements of elements, which isn't part of BEM’s intended structure.
BEM encourages creating new blocks when modifiers require multiple overrides, avoiding excessive specificity and style overrides.
Blocks and elements should be kept separate to avoid style bleeding in component-based systems like React.
Blocks can function as elements or other blocks simultaneously, allowing for modular and scalable design systems.
Mistake: creating overly complex blocks with too many elements or blocks that aren't reusable.
Transcripts
in one of the previous videos I said
that it takes a few minutes to learn bam
and when I rewatched that video my
immediate thoughts were dude if you're
so smart why don't you explain them in a
few minutes so that's what we're doing
today let's address the elephant in the
room CSS is hard you need to know a lot
of things to write good Styles you need
to know different types of selectors Box
model formatting contacts Flex box grid
and just diving into Styles and starting
to write what comes to mind first
quickly lead to Spaghetti code that is
not systematic that's hard to maintain
so that's why Engineers came up with CSS
methodologies CSS methodology is
basically just a fancy way of saying a
set of rules that you follow when you
write Styles and bem is just one of them
bem seems a little annoying at the
beginning because it has this weird
syntax with double underscore Double
Dash but once it clicks you realize that
maintaining project written in BM is so
easy you don't have this Butterfly
Effect when you change one thing on one
side of the project and something else
like completely unrelated Brak so b
stands for Block element modifier and
let's focus on blocks for now a block is
a single potentially reusable part of
the layout and let's go through an
exercise of identifying blocks in this
layout so the most obvious are button
card and grid so why are these
considered blocks
because you can take them and use them
in different layouts and context even
here you can see the button is used
inside cards and as a CTA at the bottom
of the page and all of these blocks uh
except for the grid which is a special
case which we'll cover shortly can
function on their own meaning that
semantically they could work as a as a
single unit okay so once we've
identified which parts of the layout
will convert into blocks we need to give
them names and one tip I can can give
you for naming um entities in B is to
describe the layout instead of content
here's what I mean so we have this page
about parks in Ontario one thing we
could do is name the card a park card
that would work for this page because
it's only about Parks but imagine if you
want to reuse this card component on a
different page that's about lakes in
Ontario that would not work semantically
because Park and Lake is not the same
thing so always try to describe the
layout in the name of the BL instead of
describing content now let's briefly
pause on why grid is a special case the
reason for that is that it cannot stand
on its own semantically its value is
purely functional it works as a
container for holding other blocks but
because it's such a common pattern it
makes perfect sense to abstract it as a
single block okay so I hope that's clear
blocks reusable parts of layout either
semantic or functional like a grid now
let's move on on to elements so an
element is something that exists only
within the context of a block and
doesn't work on its own when I say
doesn't work on its own I mainly mean
three things it doesn't have a semantic
meaning on its own it doesn't have a
function on its own and it has styles
that only make sense inside the context
of a block so let's consider this button
for example it has a label and an icon
so why doesn't this icon can make sense
outside the button essentially like what
function would it serve it doesn't carry
semantic meaning right it's just an
arrow like it could point at something
but I guess like if there's no something
like what's the meaning of it if it
didn't have a meaning its margin would
mess up reusability and we'll cover that
a little later so in B terminology the
label and the icon are the elements of
the button and we identify them with the
double underscore notation so again to
summarize block reusable part of the
layout works on its own uh either
semantic or functional meaning element
part of the block that doesn't work on
its own so I hope that's clear so before
we jump into modifiers Let's uh cover
the CSS implementation one of the core
principles of bem is to keep specificity
very low therefore in CSS we avoid
nesting and there are some exceptions
but uh in general we avoid nesting and
instead we use just a single class
selector for both the block and an
element and we put them at the top level
of the style sheet and that's why it's
called Flat we keep it at the at the
same level there's no nesting there's no
concatenated selectors nothing okay so a
modifier is another bem entity it
represents a change of a state or a
slight visual modification of either a
block or an element so let's say we want
to have a different style for a button
here that isn't orange but Green in then
we would create another class for this
it could look something like this button
Double Dash green and Double Dash is a
standard notation for modifiers in HTML
we would put that on the same Noe as the
button and same low specificity approach
applies in CSS we would put modifiers on
the same level as the block and an
element and the override will still work
here because button green is declared
after the button so Styles inside button
green Will trump Styles and button and
if you want to avoid overriding uh
Styles alog together you can introduce a
default modifier which will contain only
the Declarations that you later change
with auto modifiers now that we've
covered the basics I want to answer a
few common questions that come up when
you first start using them the first one
is can I use the modifier with an
element yes I have already covered that
but let's dive a little deeper here so
we have this page with all the parks and
let's say we want to highlight Al bin
and make the card stretch for two
columns so you create a modifier that
looks something like this and now we can
take this class and apply it to a
corresponding element in the HTML and it
will make sure that the cell is
stretched and another tip while we're
here notice how the cart handles
different widths easily we should always
strive to create blocks in isolation
with an idea that we don't know the
context where they will be used like
here for example it could be a narrow
column it could be a white column and it
still works how do I decide whether to
use a modifier or create a new block no
hard rule here but my rule of thumb is
that modifiers should be used for
changing just one property or like two
at Max like it could be color or size or
B and let me give you an example see how
the card looks bigger but the entire
layout looks a little bit off we have
this uh card on the right that's super
tall and we should probably change the
main card that we want to highlight to
something that looks more like this and
you might be thinking okay so like we
have the card block right like this
looks very similar because it has the
same elements so we would create a
modifier that says card overlay and we
would Nest each element of the original
card block inside and provide new styles
for it this code stinks though because
not only we create a lot of overrides we
are raking up specificity and the more
nesting we start adding to this uh block
the harder it is to read and imagine
it's just one modifier now but what if
we had another variation to the card
like it's going to be two three or four
and also imagine if you need to update
the default card Styles let's say uh you
want to add padding to an image now you
do that and this update will propagate
automatically to all of the variations
that You' have created in our cases one
but it could be more so usually when I
find myself creating a lot of overrides
I create a new block instead of a
modifier so in this case I would create
a new block that would be called overlay
card and we would nicely keep them
separate in case I want to update the
original card I updated overlay card
stays intact and same goes for overlay
card another question can block be an
element at the same time the answer is
yes to illustrate this let's go back to
our grid basically each great item can
also be a card now should you combine a
block and an element on the same note I
don't do this very often because we are
rarely writing plain HTML usually we're
working in the context of some kind of
content management system or react
framework and card usually would be its
own component if you are a front Ender
and you're writing this code in PL HTML
first and handing it to a back Ender or
someone who will be implementing it they
might take grid item and card and put
inside a component and that would create
a lot of frustration because styles from
grid item will bleed into a component
usually I separate those two and make
sure that the card sits on its own node
so logical next question can block be
another block at the same time and the
answer is also yes and I have this code
to illustrate this in this same example
you see that we have container block and
content flow block one is basically
defining the width of the content inside
and side gutters and CF flow defines the
vertical Rhythm so they both do
different things they they're not
conflicting so they could technically
leave on the same node can B be used
with uh utility classes I don't see why
not even though it sort of goes against
the B philosophy I do it all the time
because utility classes could be
extremely helpful when used in
moderation for example in our project I
have a utility class called visually
hidden a common method for hiding an
element visually but keeping it
accessible for screen readers I want the
call to action to say learn more about
gangin Park but I don't want the links
to say that entire phrase so I hide
about Al gonin Park in this utility
class I could have made this another El
inside the button but since this is such
a common pattern it makes perfect sense
to abstract it into utility class the
main point with utility classes is
staying consistent so if you start using
this visually hidden class make sure
that you use this instead of elements or
modifiers okay so these are common
questions that I could think of on my
own if you have more questions about bam
don't hesitate to ask in the comments
I'll respond every single one of them
now now bear with me we have one more
section about common mistakes and this
is very important so the first one is
using margins on blocks and let me
explain why this is such a big deal
consider this example let's put a form
at the bottom of our page it looks okay
right but the space between the button
and the form is uh like sort of tiny so
we might think let's just add some space
above by Eddie margin block start to
newsletter form block and it looks
perfectly fine now there's more space
and you might not even face any issues
if you don't reuse the newsletter form
anywhere else problems begin when you
actually start reusing the form so see
we have this empty space in the grid
after we changed the alonquin park this
overlay card you get a message from your
designer or your PM or the client and
they say why don't we put our form in
there and you take the form you put it
in and you see that now you have the
space at the top that comes from the
block itself and this can cause big
headaches in real projects because this
form could be used in hundreds or
thousands of pages and simply removing
the margin will introduce a lot of
regressions and unless you have a very
robust testing system in place it can be
very scary to change stuff like that so
what we usually do in these cases we
create a patch right GD item newsletter
form and we reset the margin and then we
add another patch for another block and
another one and another one and another
one you see how quickly it turns into a
spaghetti mess of styles never Ed
margins on blocks that messes up
reusability big time okay so next
mistake I see people make with bam is
nesting classes in CSS and it looks
something like this this defeats the
purpose of bam because the whole point
of this underscore and Double Dash
notation is to keep Styles flat and
spefic specificity low so if we do this
we basically increase specificity of
elements for no particular reason you
should always try for low specificity
and flat Styles and avoid nesting like
this concatenating selectors can also go
into this bucket it's a terrible pattern
because you make elements unsearchable
and I made the entire video why it's
okay so next mistake I want to cover is
using bem entities like utility classes
so here's a quick example we have
overlay card CTA element that looks
something like this and it has only one
uh declaration margin block start Auto
just because it has only one declaration
doesn't mean that we should copy this
class and use it on any HTML element
that needs this style this goes against
B principles because it prioritizes
Styles over semantics and that's not how
how bem works okay next mistake and I've
seen this a lot creating elements of
elements you look at the markup of the
card and you think that okay so since
image is inside media we'll just keep
doing the same pattern with double
underscore that might be some kind of
CSS methodology but that's not bam
instead of this we should just keep one
level of elements regardless of how
deeply they nested okay and the last
mistake I want to cover today is
creating blocks that have too many or
too few elements remember how in our
project we have a grid block and a card
block and card block does its own thing
grid block does its own thing what we
could have done instead is create a
single block that does both if we did
that we would end up with a block that
has nine elements not only this could be
hard to scan because the CSS file will
become too big we're also missing out on
creating a system by abstracting two
blocks that do uh different things
similar concept applies to creating
blocks that are not reused at all so for
example we could have abstracted card
content into a single blog but if we're
not reusing anywhere what's the point so
this was bem in a nutshell if you have
any other questions about it feel free
to ask in the comments and thank you
everyone who subscribed to my channel we
just crossed A8 100 subscribers doesn't
seem like a lot in YouTube universe but
for me this is a big deal it just makes
me want to continue
making these videos as helpful as I can
and again thank you so much and I'll see
you in the next one
5.0 / 5 (0 votes)