HisDivineShadow HisDivineShadow - 1 month ago 7
CSS Question

CSS selector priority from different stylesheet files

I have a page with a form with input and textarea elements. I am using bootstrap along with my own site.css. The site.css is before the boostrap.css in the markup. I have a css rule in the site css that looks like this:

.formcontainer input, textarea {
background-color: lightgray;
}


The form elements also have the form-control class from bootstrap applied to them. The problem is that the input elements prioritize the rule from my site css and apply the background color correctly. However, for the textarea elements the bootstrap class is prioritized over the rule from my site.css. All form elements are wrapped in the same div containers with the same clasess applied. I can't make sense of why the elements are getting the rules prioritized differently.

Here's an example of the markup where the input gets the background color but the textarea doesn't:

<div id="formpart2" class="formcontainer">
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Email</label>
<div class="input-group">
<input type="text" class="form-control invalid" fieldrequired>
</div>
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Contact Instructions</label>
<div class="input-group">
<textarea type="text" class="form-control" rows="10" cols="15" fieldrequired></textarea>
</div>
</div>
</div>

Answer

In Bootstrap, you might find a rule that starts something like this:

.formcontainer input, 
.formcontainer textarea {
    /* whatever */
}

In your attempt to overwrite that, you forgot the context for textarea:

.formcontainer input, 
textarea {
    background-color: lightgray;
}

This makes your rules for textarea less specific than Bootstraps's rule, so even if you load the css files in the correct order, your textarea style won't overwrite Bootstrap's textarea style (assuming you are in a .formcontainer context).

I highly recommend you learn more about CSS specificity. Very fundamental if you ever want to work with CSS.