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

前端 未结 18 864
借酒劲吻你
借酒劲吻你 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.

提交回复
热议问题