7

All,

Is there any way to define a custom CSS class that uses existing bootstrap classes?

For example, consider the following HTML snippet:

<div class="text-primary center-block">Here is some text</div>

Bootstrap will automatically make it blue and centered and displayed block. But adding all of those classes is a lot to remember. Can I just use my own class:

<div class="my_class">Here is some text</div>

And somehow in a CSS file add those Bootstrap properties?

The only solution I can think of is using JQuery like this:

$(document).ready(
  function() {
    $(".my_class").each(function() {
      $(this).addClass("text-primary center-block");      
    });
  }
);

But is there a better solution?

2
  • 1
    No, you cannot extend a CSS class. Commented Jul 21, 2015 at 23:33
  • 1
    your jQuery code could be simplified to $(".my_class").addClass("text-primary center-block") Commented Jul 21, 2015 at 23:58

2 Answers 2

9

Hi yes there is a better way, if you are using the Less Source version of Bootstrap you can setup Bootstrap's Classes as Less Mixins by importing the Less files as a Reference

Which would mean you could setup something like this:

 .custom-class { .text-primary; center-block; }

This post discusses the technique in detail:

http://transmission.vehikl.com/using-bootstrap-as-a-semantic-mixin-library/

Sign up to request clarification or add additional context in comments.

1 Comment

This sounds very promising. I will look into it and get back to you.
5

You can do the following: but this is work with SCSS not with the standard CSS

.my_class
{
    @extend .text-primary; 
    @extend .center-block;
}

Hope it helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.