"Modifying the button color in Bootstrap version 4: A step-by-step

Is there a way to change the primary button color in bootstrap v4 without affecting the theme color for all other components? I want to set the primary button color separately from the theme color without having to use brand-primary. Are there any alternative methods to achieve this?

Answer №1

Latest Update for Bootstrap 4 and Beyond

If you're working with Bootstrap 4 and its SASS functionality, adjusting the color of buttons is now simpler than ever using the versatile button-variant mixins. To customize only the primary button's color without affecting the entire theme, leverage these unique SASS features. Feel free to experiment with different values for $mynewcolor, as well as the lighten() and darken() functions.

$mynewcolor:teal;

.btn-primary {
    @include button-variant($mynewcolor, darken($mynewcolor, 7.5%), darken($mynewcolor, 10%), lighten($mynewcolor,5%), lighten($mynewcolor, 10%), darken($mynewcolor,30%));
}

.btn-outline-primary {
    @include button-outline-variant($mynewcolor, #222222, lighten($mynewcolor,5%), $mynewcolor);
}

Check out this live SASS demo here

The SASS code above compiles into the following CSS output...

.btn-primary{color:#fff;background-color:teal;border-color:#005a5a}

.btn-primary:hover{color:#fff;background-color:#004d4d;border-color:#009a9a}
.btn-primary:focus,.btn-primary.focus{box-shadow:0 0 0 .2rem rgba(0,90,90,0.5)}
.btn-primary.disabled,.btn-primary:disabled{color:#fff;background-color:teal;border-color:#005a5a}
.btn-primary:not(:disabled):not(.disabled):active,.btn-primary:not(:disabled):not(.disabled).active,.show>.btn-primary.dropdown-toggle{color:#fff;background-color:#00b3b3;border-color:#000}
.btn-primary:not(:disabled):not(.disabled):active:focus,.btn-primary:not(:disabled):not(.disabled).active:focus,.show>.btn-primary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(0,90,90,0.5)}

.btn-outline-primary{color:teal;background-color:transparent;background-image:none;border-color:teal}.btn-outline-primary:hover{color:#222;background-color:#009a9a;border-color:teal}
.btn-outline-primary:focus,.btn-outline-primary.focus{box-shadow:0 0 0 .2rem rgba(0,128,128,0.5)}
.btn-outline-primary.disabled,.btn-outline-primary:disabled{color:teal;background-color:transparent}
.btn-outline-primary:not(:disabled):not(.disabled):active,.btn-outline-primary:not(:disabled):not(.disabled).active,.show>.btn-outline-primary.dropdown-toggle{color:#fff;background-color:#009a9a;border-color:teal}
.btn-outline-primary:not(:disabled):not(.disabled):active:focus,.btn-outline-primary:not(:disabled):not(.disabled).active:focus,.show>.btn-outline-primary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(0,128,128,0.5)}

View the CSS demo generated by this Sass code


If you wish to modify the primary color across all contextual classes (such as bg-primary, alert-primary, etc.), refer to: Customizing Bootstrap CSS template and How to change the bootstrap primary color?

Additional resources:
Discover more on theming Bootstrap
Explore how to create a custom Bootstrap theme

Answer №2

To customize the colors in Bootstrap 4, you can modify them by adjusting variables in the sass files.

$theme-colors: (
   primary: red,
);
@import "~bootstrap/scss/bootstrap";

If you use the same keys for your custom colors as Bootstrap's default colors, you will override them. However, if you use new keys, you will create new classes.

In this specific example, the primary color has been changed from blue to red.

Answer №3

Give this technique a shot

Include a class to the button, such as custom-btn, and specify the corresponding CSS in our stylesheet.

.btn-primary.custom-btn {
background-color: #000;
border-color: #000;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container">
<button type="button" class="btn btn-primary custom-btn">Custom</button>
  <button type="button" class="btn btn-primary">Default</button>
</div>

Answer №4

According to the guidelines provided by bootstrap's documentation

Bootstrap’s components are primarily structured using a base-modifier class system. This approach ensures that most of the styling is applied through a base class (such as .btn), while variations in style are achieved through modifier classes (like .btn-danger). These modifiers are created based on the $theme-colors map, allowing for easy customization of the number and names of our modifier classes.

Therefore, changing the theme color will have a widespread impact.

If you wish to utilize a specific color in other parts of your project, consider adding it to the $theme-colors variable.

Answer №5

I encountered a similar issue where I wanted the button to synchronize with its container's colors.

To address this, I devised a btn class that automatically adjusts to match the parent's color upon page initialization. The outcome has left me quite satisfied (so much so that I am in the process of developing a small plugin). You can view the JSfiddle here

/*
** Created by: Jean-Marc Zimmer
** License: MIT
*/

$(function() {

  const hexDigits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];

  function hex(x) {
    return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
  }
  function hexify(rgb) {
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
  }
  function darken(rgb) {
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    return "rgb(" + parseInt(0.9 * rgb[1]) + ',' + parseInt(0.88 * rgb[2]) + ',' + parseInt(0.87 * rgb[3]) + ')';
  }

  function getParentBackground($elem) {
    var color = $elem.css("background-color");
    if (color && color !== 'rgba(0, 0, 0, 0)')
      return color;
    return ($elem.is('body') ? false : getParentBackground($elem.parent()));
  }

  function getParentColor($elem) {
    var color = $elem.css("color");
    if (color && color !== 'rgba(0, 0, 0, 0)')
      return color;
    return ($elem.is('body') ? false : getParentColor($elem.parent()));
  }

  $('.btn-negative, .btn-outline-negative').each(function() {
    var bgColor = hexify(getParentBackground($(this).parent()));
    var color = hexify(getParentColor($(this).parent()));
    var rgb = getParentColor($(this).parent());
    this.style.setProperty('--btn-negative-color0', bgColor);
    this.style.setProperty('--btn-negative-color1', color);
    this.style.setProperty('--btn-negative-shadow-color', color + "88");
    this.style.setProperty('--btn-negative-color2', hexify(darken(rgb)));
    this.style.setProperty('--btn-negative-color3', hexify(darken(darken(rgb))));
  });

});
/*
** Created by: Jean-Marc Zimmer
** License: MIT
*/

.btn-negative::before,
.btn-outline-negative::before {
  --btn-negative-color0: #fff;
  --btn-negative-color1: #000;
  --btn-negative-color2: #000;
  --btn-negative-color3: #000;
  --btn-negative-shadow-color: #0008;
}

.btn-outline-negative {
    background-color: var(--btn-negative-color0);
    border: solid 1px var(--btn-negative-color1);
    color: var(--btn-negative-color1);
}

.btn-negative,
.btn-outline-negative.active,
.btn-outline-negative:hover:not(.disabled):not([disabled]),
.btn-outline-negative:active:not(.disabled):not([disabled]) {
    background-color: var(--btn-negative-color1);
    color: var(--btn-negative-color0);
}

.btn-negative.active,
.btn-negative:hover:not(.disabled):not([disabled]),
.btn-negative:active:not(.disabled):not([disabled]) {
    background-color: var(--btn-negative-color2);
    color: var(--btn-negative-color1);
}

.btn-negative.active:hover,
.btn-negative:hover:active:not(.disabled):not([disabled]) {
    background-color: var(--btn-negative-color3);
    color: var(--btn-negative-color1);
}

.btn-negative:focus,
.btn-outline-negative:focus {
    box-shadow: 0 0 0 .2rem var(--btn-negative-shadow-color);
}
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" />
<script src="https://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" type="text/javascript"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" type="text/javascript"></script>

<div class="container">
    <div class="alert alert-success">
        <p>Some text...</p>
        <button class="btn btn-success">btn-success</button>
        <button class="btn btn-negative">btn-negative</button>
        <button class="btn btn-outline-success">btn-outline-success</button>
        <button class="btn btn-outline-negative">btn-outline-negative</button>
    </div>
</div>

The snippet's CSS call order may lead to incorrect style application.

If you have any suggestions on how to enhance it, please feel free to share!

Answer №6

To change the button style, you can either create a custom CSS sheet and override the default button styles, or add a new class to the button and override specific properties.

<button class="btn-primary">Button</button>

.btn-primary{
    background-color: teal;
}

<button class="btn-primary custom-btn-class">Button</button>

.custom-btn-class{
     background-color: teal;
}

Answer №7

<a  class="btn btn-primary" href="#">Learn more</a>



.popular  .btn-primary {
     font-weight: bold;
     background-color: red;
}

Simply modify the css and it should function properly

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Hide when reaching the end with d-none

One of the challenges I'm facing is aligning a button to the right side of a column while still utilizing d-none to control its display. Previously, I used d-flex justify-content-md-around justify-content-lg-end for alignment before adding d-none, but ...

Measuring the quantity of 'table' elements with jQuery

This HTML code below defines a table structure. Now tables can be dynamically added to this structure. <div class="tableStyle myWebsiteTable"> <table cellspacing="0" cellpadding="0" id="site0" class="site active"> <thead> ...

The top navigation menu is positioned above the sidebar menu due to a CSS error

Having an issue with adding top and side menus. The top menu is displaying above the side menu. Can someone help fix the css? Here is my fiddle. I attempted to apply #leftPanel position:fixed but it did not work as expected. ...

Badges shifting down to the next row - using Bootstrap

For my project, I have implemented a Bootstrap badge to showcase the price list. However, on mobile devices, the price list gets cut off as it moves to a new line. https://i.sstatic.net/9PyU5.jpg Mobile: https://i.sstatic.net/clOZR.jpg I am looking for ...

Retrieving Information from Bootstrap 3 Modal Form Using jQuery AJAX

i created this code to collect form data from a Bootstrap modal and send it to a PHP page for processing. However, I encountered an issue where the script was unable to retrieve values from the modal form. Unfortunately, I am unable to upload the PHP par ...

Dynamic HTML and CSS Table Alignment Techniques

Issue Screenshot: Is there a way to properly align the right column of the table, particularly the Student NRIC row and School's? .formstyled { width:70%; margin-left:5%; } .formstyled input[type=text],input[type=password],text ...

Replace the default MailChimp stylesheet with a different stylesheet

Objective: I want to modify the background color of the "Subscribe" button on a MailChimp embedded sign-up form found on our company's website page. Query: MailChimp provides the CSS hook "input.button" for styling the Subscribe button. How can I uti ...

Issue with positioning in IE11 when using `top:0` and `bottom:0` inside a table

Expanding on a previous inquiry of mine, I have created this interactive demo The demo features two columns on top of one column in smaller views, and 3 columns in a row in larger views. While the layout functions as intended, I noticed a lack of spacing ...

How to customize the background color in a Thymeleaf select element

Here is the HTML code I am working with: <select th:field="*{status.health}" th:value="${status.health}" th:class="health_color" th:name="status_healt ...

"Utilize Bootstrap 4 to create a 5-column row layout featuring lengthy text

I'm familiar with how bootstrap 4 uses col instead of col-xs, but I've encountered an issue. When the text within a column is too long to fit on a small screen, the columns begin to stack below each other. Is there a way to prevent this and set t ...

I want to create a custom jQuery slider totally from scratch

Greetings everyone, I have been tasked with creating a slider using only HTML / jQuery code. Here is the template: And here is the HTML code for the template above: <div id="viewport-container"> <section id="sliding-container"> & ...

Ways to prevent an element from being affected by a CSS Bootstrap class

Is there a way to exclude the container class from affecting the jumbotron class in Bootstrap 4? In my PHP project using the MVC pattern, I have a header included on every page that ends with <main class="container">. However, on the home page, I wa ...

Adjusting the width of rows in tables for th and td elements

Hi there, I'm having trouble with aligning the data inside a table. The table alignment seems off, and I'm struggling to fix it. Can anyone lend a hand with this? The only thing I can't remove is the height: calc(100vh - 346px); as it's ...

Beginner in CSS wanting to set background image for input field

I am working on incorporating icons into my project. The image I have contains an array of 16x16 icons at this URL: "http://www.freepbx.org/v3/browser/trunk/assets/css/jquery/vader/images/ui-icons_cd0a0a_256x240.png?rev=1" Does anyone know how I can selec ...

Why do CSS changes in Chrome Console only take effect locally and not when the website is live?

I recently encountered an issue where I wanted to incorporate negative margins into a specific section of my website, as seen in the Chrome Console (link to image): .woocommerce div.product div.images .woocommerce-product-gallery__wrapper { -webkit-tr ...

flexible side-by-side alignment - adaptable grids

I am currently working on a website project that involves a ul list with responsive columns. The column width adjusts based on the window size, and I aim to center-align the text within the li element according to the new column width. If you want to view ...

Partial display of Datetimepicker options puzzling users

I'm having some trouble getting the datetimepicker to work. I followed the installation instructions which can be found here. After installing the package with bower and linking all the necessary stylesheets and js files, I encountered an issue where ...

Modifying the color of an empty string is not feasible in Javascript

Is it possible to change the color of FirstName only when there is text input? Currently, it turns green when there's text, but I want it to turn red when it's empty. How can this be achieved? $(document).on("click", '.btn-info.mailCo ...

Switch the position of the bootstrap dropdown menu to a different side

How can I move the Bootstrap dropdown menu to the left side, as shown in the screenshot below? Disregard the color differences in the code snippet and screenshots. https://i.sstatic.net/nrgHF.png https://i.sstatic.net/d24He.png <head> ...

Is there a way to specifically target the accordion panel header of Bootstrap upon being clicked?

I am currently utilizing Bootstraps collapse (accordion) feature and I want to modify the background color of the .panel-header when it is open. My current code snippet is close, but I have encountered an issue. $('.panel-group').on('show.b ...