Search code examples
cssborder

how to prevent shifting when changing border width


here is a fiddle.

http://jsfiddle.net/86juF/1/

how do I prevent the elements from appearing to shift on click?

The elements normally have a 1px border but go to a 2px border on click.

In the fiddle you will see this css

.o {
    height: 50px;
    width: 100px;
    border: 1px solid red;
    margin-bottom: 10px;
    font-weight: bold;
    font-size: 16px;
}

.selected {
    border: 2px solid blue;
}

Solution

  • While you've already accepted an answer, which works, it seems rather more complicated than it needs to be, having to calculate and adjust margins and such; my own suggestion would be to make the border itself transparent, and use a fake 'border', using box-shadow (which doesn't cause any movement since it's not part of the 'flow' as such):

    .o {
        /* no changes here */
    }
    
    .o.selected {
        border-color: transparent; /* remove the border's colour */
        box-shadow: 0 0 0 2px blue; /* emulate the border */
    }
    

    JS Fiddle demo.