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

后端 未结 18 1540
情话喂你
情话喂你 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:39

    I needed to be able to "border" any element by adding a class and not affect its dimensions. A good solution for me was to use box-shadow. But in some cases the effect was not visible due to other siblings. So I combined both typical box-shadow as well as inset box-shadow. The result is a border look without changing any dimensions.

    Values separated by comma. Here's a simple example:

    .add_border {
        box-shadow:-1px 0 1px 1px rgba(0, 0, 0, 0.75), inset -1px 0 0 1px rgba(0, 0, 0, 0.75);
    }
    

    jsfiddle

    Adjust for your preferred look and you're good to go!

    0 讨论(0)
  • 2020-12-07 15:42

    You can do some fancy things with inset shadows. Example to put a border on the bottom of an element without changing its size:

    .bottom-border {
      box-shadow:inset 0px -3px 0px #000;
    }
    
    0 讨论(0)
  • 2020-12-07 15:46

    Try this

    box-sizing: border-box;
    
    0 讨论(0)
  • 2020-12-07 15:48

    We can also use css calc() function

    width: calc(100% - 2px);
    

    subtracting 2px for borders

    0 讨论(0)
  • 2020-12-07 15:49

    You can create the element with border with the same color of your background, then when you want the border to show, just change its color.

    0 讨论(0)
  • 2020-12-07 15:51

    I usually use padding to resolve this issue. The padding will be added when border disappears and removed when border appears. Sample code:

    .good-border {
      padding: 1px;
    }
    
    .good-border:hover {
      padding: 0px;
      border: 1px solid blue;
    }
    

    View my full sample code on JSFiddle: https://jsfiddle.net/3t7vyebt/4/

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