why does changing the `background-color` of a button change other styles too?

前端 未结 3 1417
别那么骄傲
别那么骄傲 2020-12-11 16:08

http://codepen.io/anon/pen/KwKOaz

Changing only the background-color significantly changes the style on a button element, specifically the border<

相关标签:
3条回答
  • 2020-12-11 16:34

    Browser vendors apply custom styling to UI elements like buttons and input fields. Altering one of these overwritten attributes results in disabling all of the other vendor styles on that element as well. If you want to change one attribute, you have to alter the others as well, I'm afraid.

    Unfortunately I can't tell you why they do this - probably there is might be some spec behind, but I cannot find any evidence for that.

    0 讨论(0)
  • 2020-12-11 16:34

    Sometimes CSS styles are inherited. However, you are applying styles to your body which is everything in HTML. Personally I don't apply anything to body other than maybe reset or normalize CSS. That said, you can use CSS selector operators and\or id/classes to minimize:

    http://www.w3schools.com/cssref/css_selectors.asp

    Example:

    html

    btw don't write html like this just easier to read

    <body>
        <div class="wrapper">
              <button class="all-btns red">
                  Cancel
              </button>
    
              <button class="all-btns green">
                   Save
              </button>
        </div>
    </body>
    

    css

    .div.wrapper {
        width: 100%;
        height: auto;
        background: #efefef;
    }
    
    .all-btns {
        border: solid 1px #000; 
        width: 50px;
        line-height: 48px;
        height 35px;
        color: #fff;
    }
    
    .btn.red {
        color: #fff;
        background: red;
    }
    .btn.green {
        background: green;
    }
    
    0 讨论(0)
  • 2020-12-11 16:46

    When all the styles are untouched, the browser uses the host OS's given API to render the given control. This will make the control look native to the platform, but if you apply any style to that control/element, the browser cannot guarantee that the given style can be applied in the given platform, so it defaults back to a simplified, fully css solution.

    Also note, that styling control elements, though works, not covered by stable standards yet.

    For example, the NSButton (native control behind the button in OS X) doesn't have an option to set the background color, so the browser faces an impossible task. On Windows, you can change the background color, this is why people report not seeing your issue on Windows.

    0 讨论(0)
提交回复
热议问题