I use Bootstrap as a starting point for a lot of the themes that I build as a great starting point for reusable components. But one of the problems I’ve run into is trying to integrate Gravity Forms with Bootstrap. By default, Gravity Forms does not include Bootstrap classes, so the two don’t end up working very well together.
Fortunately, with a little bit of elbow grease, there’s a way to tweak Gravity Forms markup and styles to match a default Bootstrap form. The solution I’ve found is a combination of a single hook and some SASS / CSS tweaks to get everything off the ground.
For reference, a typical Bootstrap form should be marked up something like this:
[snippet slug=bootstrap-form-default-markup lang=html]
I’m using version 4 of Bootstrap, but things are pretty much the same in older versions of Bootstrap as well. There are really two things that are important in this markup. The first is that a class of
form-group is used on an input’s wrapper element (
fieldset in this case). The second is that a class of
form-group is added to each input. Cool, let’s step through this.
The first step is to wrap inputs in an element with a class of form-group then. That’s actually pretty simple. There’s a Gravity Form filter called
gform_field_container that can be used to change the markup of the list item for each input. So all we have to do is ensure that the form-group class is added here, which we can do with a simple one-line function:
[snippet slug=gravity-forms-filter-input-wrapper lang=php]
Now each input will be wrapped in the proper form-group class, along with any classes Gravity Forms wants to add.
The second part, adding a form-group class to every input element, is a little trickier. There are actions that let you edit the actual markup of inputs, but there’s nothing that just lets you filter input classes, which means you’ll end up rewriting the entire input function. Things get complicated fast, and I just haven’t found that to be a very smart way to go. Here’s the solution I’ve found works best: Instead of adding Bootstrap classes to Gravity Forms, we customize Gravity Forms classes to match Bootstrap classes.
If you’re using SASS, this is super easy thanks to @extend, which allows you to apply styles from one class to another. So we just need to extend Bootstrap styles to the Gravity Form’s CSS. Which looks like this:
[snippet slug=gravity-forms-bootstrap-sass lang=bash]
This will apply the styles from Bootstrap classes to the proper elements inside of Gravity Forms and make everything look just as it should. You may need to tweak a bit here and there on individual elements but this tends to get things working pretty well.
Looking for the fully compiled, vanilla CSS version of this? I set up a gist for you to drop into your project.
Note: Updated on August 22, 2016. Thanks to Josh Cranwell for some much-needed additions!