Set div outerwidth using css

后端 未结 5 661
名媛妹妹
名媛妹妹 2021-01-02 00:48

I wonder if there is way to set outerwidth of a div using css to ignore padding and borders.

When I set a div t

相关标签:
5条回答
  • 2021-01-02 01:21

    Nest another div inside yours, and apply the paddings/borders to the nested one:

    <div style="width:50%;"> <div style="padding:5px;">  ....  </div> </div>
    

    Unfortunately, there is no purely CSS way to achieve that (or at least I'm not aware of one).

    0 讨论(0)
  • 2021-01-02 01:31

    I'm wonder if there is way to set outerwidth of a div using css to ignore padding and borders.

    You can use box-sizing: border-box to make padding and border be counted inside width:

    div {
        box-sizing: border-box;
    }
    

    See: http://jsfiddle.net/thirtydot/6xx3h/

    Browser support: http://caniuse.com/css3-boxsizing

    The spec: http://www.w3.org/TR/css3-ui/#box-sizing

    0 讨论(0)
  • 2021-01-02 01:31

    I am assuming you don't want to add more elements and answer your question slightly differently.

    1. The browser, not the style-sheet, determines the actual size of relative measurements such as em and %.
    2. There is no common/standard mechanism to feed calculated data from the browser's internal layout engine back into a stylesheet (this could be a dangerous looping problem).

    Truly, the only way to do this is to:

    1. Use fixed width sizes and add pixel calculations into your style.
    2. Use JavaScript or related framework to achieve the results.
    0 讨论(0)
  • 2021-01-02 01:38

    you could split the 50% value assigned to the width as this:

    width: 46%;
    
    margin: 0 1%; // 0 top/bottom and 1% each for left and right
    
    padding: 0 1%; // same as above
    

    you can recalculate the percentages to suit your needs, as long as the total is 50% you should be fine.

    I would avoid using js to fix small cosmetic issues as this would not work with js off and would add extra workload to your client's browser - think of mobile and you will see why performance counts!

    0 讨论(0)
  • 2021-01-02 01:39

    I would simply add a div inside that div if possible.

    <div id="outerwidth">
      <div class="inner">
       //Content
      </div>
    </div>
    
    .outerwidth { width: 50%; }
    .inner { padding: 20px; }
    
    0 讨论(0)
提交回复
热议问题