Paul Samsotha
Paul Samsotha

Reputation: 209004

Is there a way to put a border inside an Element instead of Outside?

Im working with jQuery and CSS. When I use a mouseenter event for an image (to put a border around the image), the layout gets tweeked because of the outside border, which makes it pretty ugly. I was just wondering if there's a way to put the border inside of the img so that the img container remains the same size and doesn't affect the layout. The only thing I can think of is to resize the image in the mouseevent, which just seems like a lot of work (figuring out sizes, especially considering responsiveness), and I can see a lot of problems arising from doing this.

Upvotes: 12

Views: 15878

Answers (4)

Gupta.Swap
Gupta.Swap

Reputation: 265

Try this -

<div>
    <div id="div2"></div>
</div>

<style>
div {
    height: 200px;
    width: 200px;
}
div#div2:hover {
    height: 196px;
    width: 196px;
    border: 2px solid black;
}
</style>

http://jsfiddle.net/ET2De/

Upvotes: 0

Mr. Alien
Mr. Alien

Reputation: 157334

Actually you cannot use border property for having a border inside an element, workaround for this is to use box-shadow set to inset

div {
    height: 200px;
    width: 200px;
    box-shadow: inset 0 0 1px #000;
}

Demo (This will generate a blurred border, to get a nice solid one, refer the demo below)


Get some more solidity

div {
    height: 200px;
    width: 200px;
    box-shadow: inset -1px 0 0 red, inset 0 -1px 0 red, inset 1px 0 0 red, inset 0 1px 0 red;
}

Demo

Upvotes: 23

Mr_Green
Mr_Green

Reputation: 41832

You can use :after pseudo element selector.

div {
    height: 200px;
    width: 200px;
    position: relative;
    border: 1px solid grey;
}

div:hover:after{
    content: "";
    position: absolute;
    left: 1px;
    right: 1px;
    top: 1px;
    bottom: 1px;
    border: 1px solid green;
}

Working fiddle

Upvotes: 4

Robin
Robin

Reputation: 7895

Adjusting the padding works.

#something {
    padding: 12px;
}
#something:hover {
    padding: 8px;
    border: 4px solid #FF0000;
}

box-shadow is not supported in older browsers.

See this JSFiddle.

Upvotes: 3

Related Questions