Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placing border inside of div and not on its edge

Tags:

html

css

border

I have a <div> element and I want to put a border on it. I know I can write style="border: 1px solid black", but this adds 2px to either side of the div, which is not what I want.

I would rather have this border be -1px from the edge of the div. The div itself is 100px x 100px, and if I add a border, then I have to do some mathematics to make the border appear.

Is there any way that I can make the border appear, and ensure the box will still be 100px (including the border)?

like image 833
TheMonkeyMan Avatar asked Mar 07 '12 12:03

TheMonkeyMan


People also ask

How do you put a border inside a div not outside?

Answer: Use the CSS box-shadow property If you want to place or draw the borders inside of a rectangular box there is a very simple solution — just use the CSS outline property instead of border and move it inside of the element's box using the CSS3 outline-offset property with a negative value.

Is CSS border inside or outside?

Width and height values apply to the element's content only. The padding and border are added to the outside of the box. padding-box : Width and height values apply to the element's content and its padding. The border is added to the outside of the box.


2 Answers

Set box-sizing property to border-box:

div {      box-sizing: border-box;      -moz-box-sizing: border-box;      -webkit-box-sizing: border-box;      width: 100px;      height: 100px;      border: 20px solid #f00;      background: #00f;      margin: 10px;  }    div + div {      border: 10px solid red;  }
<div>Hello!</div>  <div>Hello!</div>

It works on IE8 & above.

like image 132
sandeep Avatar answered Sep 28 '22 08:09

sandeep


You can also use box-shadow like this:

div{     -webkit-box-shadow:inset 0px 0px 0px 10px #f00;     -moz-box-shadow:inset 0px 0px 0px 10px #f00;     box-shadow:inset 0px 0px 0px 10px #f00; } 

Example here: http://jsfiddle.net/nVyXS/ (hover to view border)

This works in modern browsers only. For example: No IE 8 support. See caniuse.com (box-shadow feature) for more info.

like image 30
caitriona Avatar answered Sep 28 '22 06:09

caitriona