When 1 px border is added to div, Div size increases, Don't want to do that

后端 未结 18 1542
情话喂你
情话喂你 2020-12-07 15:09

On click I am adding, 1px border to div, so Div size increases by 2px X 2px. I dont want to get div size increased. Is there any simple way to do so?

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

    Just decrease the width and height by double of border-width

    0 讨论(0)
  • 2020-12-07 16:00

    You can try a box-shadow inset

    something like this: box-shadow:inset 0px -5px 0px 0px #fff

    adds a white 5px border to the bottom of the element without increasing the size

    0 讨论(0)
  • 2020-12-07 16:03

    In case content of your div is rendered dynamically and you want to set its height, you can use a simple trick with outline:

    button {
        padding: 10px;
        border: 4px solid blue;
        border-radius: 4px;
        outline: 2px solid white;
        outline-offset: -4px;
    }
    
    button:hover {
        outline-color: transparent;
    }
    

    Example here: https://codepen.io/Happysk/pen/zeQzaZ

    0 讨论(0)
  • 2020-12-07 16:05

    The border css property will increase all elements "outer" size, excepts tds in tables. You can get a visual idea of how this works in Firebug (discontinued), under the html->layout tab.

    Just as an example, a div with a width and height of 10px and a border of 1px, will have an outer width and height of 12px.

    For your case, to make it appear like the border is on the "inside" of the div, in your selected CSS class, you can reduce the width and height of the element by double your border size, or you can do the same for the elements padding.

    Eg:

    div.navitem
    {
        width: 15px;
        height: 15px;
        /* padding: 5px; */
    }
    
    div.navitem .selected
    {
        border: 1px solid;
        width: 13px;
        height: 13px;
        /* padding: 4px */
    }
    
    0 讨论(0)
  • 2020-12-07 16:06

    This is also helpful in this scenario. it allows you to set borders without changing div width

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

    Taken from http://css-tricks.com/box-sizing/

    0 讨论(0)
  • 2020-12-07 16:06

    Another good solution is to use outline instead of border. It adds a border without affecting the box model. This works on IE8+, Chrome, Firefox, Opera, Safari.

    (https://stackoverflow.com/a/8319190/2105930)

    0 讨论(0)
提交回复
热议问题