Setting div width to 100% minus certain amount of px

后端 未结 5 1454
执笔经年
执笔经年 2020-12-31 18:40

Have been searching the net for the past hours to find a solution to this, but couldn\'t find it, so here I am.

I need the width of the div to be

5条回答
  •  余生分开走
    2020-12-31 19:36

    This type of calculation isn't currently supported in CSS (certainly not in Chromium 12/Ubuntu 11.04), but there is a calc() function defined in CSS 3, which would allow for this kind of behaviour, using simple mathematical functions:

    section {
      float: left;
      margin: 1em; border: solid 1px;
      width: calc(100%/3 - 2*1em - 2*1px);
    }
    
    p {
      margin: calc(1rem - 2px) calc(1rem - 1px);
      border: solid transparent; border-width: 2px 1px;
    }
    p:hover { border-color: yellow; }
    

    (Above example taken directly from the W3.org.)

    My own (in-exhaustive) tests show:

    +----------------+-------------------+
    |  Browser       |  Ubuntu 11.04     |
    +----------------+-------------------+
    |  Chromium  12  |  Fails            |
    |  Firefox  5    |  Fails            |
    |  Opera  11.10  |  Fails            |
    +----------------+-------------------+
    

    The above results were obtained using the named browsers and a css calc() demo, the code of which is below:

    HTML:

    This is the box.

    CSS:

    #box {
        width: calc(100% - 20%);
        background-color: #f90;
        font-weight: bold;
        color: #fff;
        line-height: 2em;
        text-align: center;
        margin: auto;
    }
    

    (If anyone would like to run the above test in the browsers on their platform, and supply the results, or edit them in to this answer, that would be much appreciated.)

    As pointed out, by clairesuzy, in comments:

    [Take] a look at caniuse it does work in Firefox if you use width: -moz-calc() but that's about it ;)

    And, indeed, in Firefox 5 (Ubuntu 11.04) it does work (the other vendor prefixes don't appear to do anything for Opera or Webkit, though; sadly): Revised vendor-prefixed demo.

    Reference:

    • CSS3 Values and Units.

提交回复
热议问题