5 ms·
> Avoiding collision in CSS is so freaking easy Having spent this afternoon scratching my head over one, I'd like to know what I've missed. Take your standard
by porker 11y ago
> Avoiding collision in CSS is so freaking easy
Having spent this afternoon scratching my head over one, I'd like to know what I've missed.
Take your standard website, with a block called '.sidebar'. You want this to have default styles (font size, headings etc).
Into .sidebar (and .main, and .some-other-region) you can drop components. I like to use BEM for component naming. This one has:
.box {} and .box__header {}
My issue: given <div class="sidebar"><div class="box"><h4 class="box__header">Header</h4></div></div> the styles on .sidebar h4 {} override those on .box__header.
How does one set defaults?
- talmand 11y agoAssuming I'm understanding correctly, seems easy to me. .sidebar h4 { color: red; font-size: 20px; } .box .box__header { color: green; } <div class="sidebar"><div class="box"><h4>Header</h4></div></div> will produce red text. <div class="sidebar"><div class="box"><h4 class="box__header">Header</h4></div></div> will produce green text. Both will have the 20px font-size. It all depends on how you plan out the HTML structure and CSS selectors. EDIT: I would also say if you are placing HTML like this into the page in several places, then the CSS for it should be self-contained and totally separated fron the rest of the page. I would be reluctant to use default CSS on a container such as that. But I can see it would depend on the nature of the container.
- rrrx3 11y agoExactly. This comes from proper element definition and understanding pieces before they go onto the page to begin with. Planning out, using BEM, or OOCSS, or Atomic helps tremendously here.
- porker 11y agoPerhaps I misunderstand BEM, but .box .box__header {} seems to be against the spirit of it -- my understanding is that this naming convention exists to prevent needing to nest style rules? I agree with your edit; global styles are probably not the best here, however tempting they may be to reduce wrapper markup and make everything simpler (to begin with)
- talmand 11y agoBEM would work in this case. It's just that I wouldn't use .sidebar as the starting container for the related elements, it would be .box instead. In this example .sidebar just happens to be the container to hold other elements being placed into it. I would make .box be the actual true container of the widget I am placing inside whatever container happens to need it. My CSS would be built so that .box is the foundation and it could exist anywhere on the page.