How can I do width = 100% - 100px in CSS?

前端 未结 18 835
借酒劲吻你
借酒劲吻你 2020-12-12 13:28

In CSS, how can I do something like this:

width: 100% - 100px;

I guess this is fairly simple but it is a bit hard to find examples showing

相关标签:
18条回答
  • 2020-12-12 13:59

    There are 2 techniques which can come in handy for this common scenario. Each have their drawbacks but can both be useful at times.

    box-sizing: border-box includes padding and border width in the width of an item. For example, if you set the width of a div with 20px 20px padding and 1px border to 100px, the actual width would be 142px but with border-box, both padding and margin are inside the 100px.

    .bb{
        -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
        -moz-box-sizing: border-box;    /* Firefox, other Gecko */
        box-sizing: border-box;     
        width: 100%;
        height:200px;
        padding: 50px;
    }
    

    Here's an excellent article on it: http://css-tricks.com/box-sizing/ and here's a fiddle http://jsfiddle.net/L3Rvw/

    And then there's position: absolute

    .padded{
        position: absolute;
        top: 50px;
        right: 50px;
        left: 50px;
        bottom: 50px;
        background-color: #aefebc;
    }
    

    http://jsfiddle.net/Mw9CT/1/

    Neither are perfect of course, box-sizing doesn't exactly fit the question as the element is actually 100% width, rather than 100% - 100px (however a child div would be). And absolute positioning definitely can't be used in every situation, but is usually okay as long as the parent height is set.

    0 讨论(0)
  • 2020-12-12 14:00

    The short answer is you DON'T do this in CSS. Internet Explorer has support for something called CSS Expressions, but this isn't standard and is definitely not supported by other browsers like FireFox for instance.

    You'd be better off doing this in JavaScript.

    0 讨论(0)
  • 2020-12-12 14:02

    Could you nest a div with margin-left: 50px; and margin-right: 50px; inside a <div> with width: 100%;?

    0 讨论(0)
  • 2020-12-12 14:03

    You can't.

    You can, however, use margins to effect the same result.

    0 讨论(0)
  • 2020-12-12 14:04

    You can try this...

    <!--First Solution-->
    width: calc(100% - 100px);
    <!--Second Solution-->
    width: calc(100vh - 100px);

    vw: viewport width

    vh: viewport height

    0 讨论(0)
  • 2020-12-12 14:05
    <div style="width: 200px; border: 1px solid red;">
        <br>
        <div style="margin: 0px 50px 0px 50px; border: 1px solid blue;">
            <br>
        </div>
        <br>
    </div>
    
    0 讨论(0)
提交回复
热议问题