Monday, January 16, 2017

Namespace and extending twitter bootstrap


Using customized bootstrap styles can sometimes conflict with other bootstrap styles that are not customized, for example this could happen if you have a frame and you are loading a web component inside of it inside a page.

Possible solution to avoid conflicts is to namespace twitter bootstrap

Lets take example html with bootstrap styling

<html>
<head>
    <title>My Twitter Bootstrap example</title>
    <link rel="stylesheet" href="bootstrap.css">
</head>
<body>
    <ul class="nav nav-pills" role="tablist">
        <li role="presentation" class="active"><a href="#">Home <span class="badge">42</span></a></li>
        <li role="presentation"><a href="#">Profile</a></li>
        <li role="presentation"><a href="#">Messages <span class="badge">3</span></a></li>
    </ul>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
</body>
</html>

To namespace bootstrap styles:
Create a new less file, and paste the below inside. "mybt" below is the custom namespace i am using

.mybt {
    @import "bootstrap-3.3.7/less/bootstrap";
}

After that compile this less file
lessc mybt.less mybt.css

And now after referencing mybt.css the html would use mybt and the bootstrap styles like below

<html>
<head>
    <title>My Twitter Bootstrap example</title>
    <link rel="stylesheet" href="mybt.css">
</head>
<body>
    <ul class="mybt nav nav-pills" role="tablist">
        <li role="presentation" class="mybt active"><a href="#">Home <span class="mybt badge">42</span></a></li>
        <li role="presentation" class="mybt"><a href="#">Profile</a></li>
        <li role="presentation" class="mybt"><a href="#">Messages <span class="mybt badge">3</span></a></li>
    </ul>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
</body>
</html>

Another option is to extend bootstrap styles
to extend it, create new less file with below:

@import "bootstrap-3.3.7/less/bootstrap";

.my-nav:extend(.nav) {}
.my-nav-pills:extend(.nav-pills) {}
.my-badge:extend(.badge) {}

Extending will work if you have only few styles that you are using.

No comments:

Post a Comment