Prioritizing CSS classes?

2020-03-31 04:03发布

I'm using Twitter's Bootstrap library, version 2.0.3 to prototype a website. I'm currently using the provided modal control, albeit inline, to display what will be a form:

<div class="modal in-layout span6 offset3">
    <div class="modal-header">
        <h3>Header</h3>
    </div>
    <div class="modal-body">
        <p>Hello</p>
    </div>
    <div class="modal-footer">

    </div>
</div>

I wrote my own selector to make use of my custom class, .in-layout:

div.modal.in-layout {
    position: static;
    top: auto;
    left: auto;
    margin-top: 10px;
    margin-bottom: 10px;
}

The problem is that the CSS rules are matched in a really inconvenient order:

enter image description here

Essentially, I need the .span6 and .offset3 classes to apply with a higher priority than .modal in order to give my <div> a margin of 260px and a width of 460px.

Is there any way I can do this?

标签: html css
2条回答
Bombasti
2楼-- · 2020-03-31 04:50

There are 3 ways of making a rule override another (listed strongest to weakest):

  1. Importance, e.g. rules in author stylesheets will override those specified in user-agent stylesheets, using !important rule will override any other rule.
  2. Specificity, a rule will override any other rules with less specific selectors. Here's an article on the subject. Basically, element.class is more specific than .class, but less specific than #id.
  3. Order, a rule will override any other rules which came before it.

Aside of that, I'm spotting some other issues with your code. When designing a website, it is best to use semantics definitions ("what this means") rather then form related terms ("how this should look").

To refer to your code concretely, are naming your class names span6, in-layout and offest3, where you should probably have something like warning-modal, information-header or error-footer, which convey the meaning of the element (after all HTML's sole purpose is to give context to your text).

Once you'll think in these terms, it'll be a lot easier to design styles for your elements.

查看更多
一纸荒年 Trace。
3楼-- · 2020-03-31 04:56

Just put them after the .modal rules or repeat the rules you need from .span6 and .offset3 in your div.modal.in-layout.

查看更多
登录 后发表回答