How to add padding or border to a DIV and keep width and height?

后端 未结 5 1309
半阙折子戏
半阙折子戏 2020-12-28 18:42

Is there some way to keep a set width/height for a DIV, and pad the content without the DIV growing? See example below. I want all the boxes to be exactly 140x140.

H

相关标签:
5条回答
  • 2020-12-28 19:08

    Depending on what browsers you need to support, you could change the box-sizing attribute on these DIVs to be border-box. That will allow you to set a height and a width on each box, without the padding or borders effecting the dimensions you set.

    It has been suggested by a few people to set this globally for all elements in a reset because it makes things a lot easier to style (and is arguably a better box-sizing model than the default). To do this, you would use something like:

    * {
        -moz-box-sizing: border-box;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
    }
    

    More information, including browser support and some general warnings can be found here: http://paulirish.com/2012/box-sizing-border-box-ftw/

    0 讨论(0)
  • 2020-12-28 19:11

    Yes you can use

    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;         /* Opera/IE 8+ */
    

    to change the box model to make borders and padding internal to your width/height, but margins are still added.

    and your updated Fiddle

    more information here css tricks

    0 讨论(0)
  • 2020-12-28 19:11

    Yes the solution to your problem is box-sizing:border-box; ( http://css-tricks.com/box-sizing/ , http://paulirish.com/wp-content/uploads/2011/gplus-boxsizing.html ) (works in IE8+ and all modern browsers)

    0 讨论(0)
  • 2020-12-28 19:14

    Yes just subtract twice the padding or border from the height and width. In other words, subtract the padding or border from each side of the div:

    .box1
    {
        width: 140px;
        height: 140px;
        background: #f66;
    }
    
    .box2
    {
        width: 130px;
        height: 130px;
        background: #66f;
        padding: 5px;
    }
    
    .box3
    {
        width: 130px;
        height: 130px;
        background: #6f6;
        border: 5px solid #000;
    }
    

    fiddle example: http://jsfiddle.net/N6BYH/

    Or use box-sizing: border-box; https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing.

    0 讨论(0)
  • 2020-12-28 19:14

    The cleanest method would probably be to nest <div> tags within your current <div> tags, and apply the padding to them:

    <div class="box" id="box1"><div>Howdy.</div></div>
    <div class="box" id="box2"><div>Howdy.</div></div>
    <div class="box" id="box3"><div>Howdy.</div></div>​
    

    CSS:

    .div { /* ... */ }
    .div > div { padding: 1em; } /* Apply to all inner divs */
    #box2 > div { padding: 1em; } /* Only apply to the inner div in #box2 */
    
    0 讨论(0)
提交回复
热议问题