Style Drupal blocks by adding CSS classes

  0 comments
Share

To style a block, we need a way to target it in CSS. When we inspect a block, we find a block ID selector. We can use that to target the block in CSS. But this is not the best way to style blocks in CSS. It can very quickly become hard to maintain. There is a better way, but first, let's look at how to do with the block ID.

Consider an example, my blog which contains a blog logo and a short message.

<div id="block-block-3" class="block block-block"> <div><img src="/imagepath.jpg"></div> <div>To style a block, we need a way to target it in CSS.</div> </div>

Each block has a unique ID, called bid. In this case, the block ID is 3, so the block contains an ID of block-block-3.

You can use block-block-3 as the selector in CSS and style that block.

#block-block-3 { width: auto; padding: 10px; background-color:#CCCCFF; }

But is this the best approach? In fact, it is a bad idea for the following reasons:

Can?t always guarantee that the block ID will be correct.

Suppose you have a dev site and a live site. If a block already exists on live and you pull it down locally, you can style it using the ID. But what if blocks are added manually on different environments? You can't guarantee that the ID will always be the same.

Can?t easily reuse the same block style.

For example, suppose you have 4 blocks that require the same style. You?d end up with something like this:

#block-block-3, #block-block-4, #block-block-5, #block-block-6 { width: auto; padding: 10px; background-color:#CCCCFF; }

No doubt you will have many difficult styles grouped like this. Your CSS file is going to be unnecessarily huge and messy and hard to maintain.

Use a class name

The better approach is to add class names to the blocks.

  • Guarantee the same selector on all environments
  • Use the same style on multiple blocks by using the same class.

To add classes in blocks, Install and enable Block Class module.

You will get a CSS class(es) field where you can add your CSS class.

add block classes

The class 'right-box' is then added to the block. Now inspect that block, we will found HTML something like this:

<div id="block-block-3" class="block block-block right-box"> <div><img src="/imagepath.jpg"></div> <div>To style a block, we need a way to target it in CSS.</div> </div>

The CSS will be:

.block.right-box { width: auto; padding: 10px; background-color:#CCCCFF; }

Conclusion

Style the block using the default block IDs is enough to get the job done, but as with most things in Drupal, there is a better way. Small changes like creating block styles of Drupal site is hard to maintain for manage their content and its styling.

Add new comment