2

Bootstrap 4 has Spacing Utilities to adjust margins and paddings with simple CSS classes.

Theoretically, I could do something like this:

<div class="d-inline-block bg-inverse p-5 pb-0 m-5 mb-0"></div>

And this should be an element with paddings and margins on each side except at the bottom. Right?

But that isn't happening. Instead, pb-0 and mb-0 are being overwritten by p-5 and m-5, as you can see here: example in JSFiddle.


pb-0 and mb-0 are defined after p-5 and m-5 in the original source, and all of the attributes used in these classes have !important. So pb-0 should overwrite the padding-bottom defined by p-5 and mb-0 should overwrite the margin-bottom defined by m-5.

I created another example where I defined these classes in the same way, but in this case, they are working as expected: comparison example in JSFiddle.


Why these Bootstrap 4 classes are not working as expected?

Gerard Reches
  • 3,048
  • 3
  • 28
  • 39

1 Answers1

3

The spacing utils use !important so, using pb-0 to override p-5 isn't going to work because p-5 follows pb-0 in the bootstrap.css

To get it working like you want set the specific sides...

<div class="d-inline-block bg-inverse pb-0 px-5 pt-5 mb-0 ml-5 mt-5"></div>

And, since DIV doesn't have padding or margins by default, you don't really need the *-0...

<div class="d-inline-block bg-inverse px-5 pt-5 ml-5 mt-5"></div>

https://www.codeply.com/go/6hSIEizfMd


Also see, when it's OK to use !important

Carol Skelly
  • 351,302
  • 90
  • 710
  • 624
  • 1
    Browsers indicates `p-5` in `_spacing.scss` line 12 and `pb-0` in `_spacing.scss` line 15. But after taking a look at the bootstrap files, the `-0` classes are generated first in the `@each` loop in `_sizing.scss`. So yes, as you said `p-5` is defined after `pb-0`. But this looks like something wrong for me, I can't find a situation where you need a specific side padding being overwritten by a general padding. I solved it rearranging the `$spacers` array in `_variables.scss`. Thanks! – Gerard Reches May 17 '17 at 13:18
  • 1
    Yep, that works in your case, but others may want the reverse. For example, suppose you want to zero out the padding, and then add it back to one side eg:`
    Text
    `. Currently in BS4 this works, but if you change the order of classes it won't work,
    – Carol Skelly May 17 '17 at 13:28
  • Yeah... that's true. I was going to open a proposal on GitHub, but with your example now I have seen that there is no ideal solution for this. – Gerard Reches May 17 '17 at 14:26
  • 1
    Thanks for the insight and great question! – Carol Skelly May 17 '17 at 14:27