How can I add a CSS border inside a <div> element without increasing its overall size?

I have a <div> element with a size of 100px x 100px, and I want to add a border to it. However, using the style=“border: 1px solid black” property adds 2px to each side of the <div>, making it larger than 100px x 100px.

Is there a way to add a border to the <div> so that it remains 100px x 100px, with the border appearing inside the <div> rather than on its edges?

To achieve this, you can use the box-sizing property set to border-box. This property ensures that the border and padding of the element are included in its total width and height. Here’s an example:

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;
}

In this example, the box-sizing: border-box; ensures that the border is included in the 100px x 100px dimensions of the

, preventing it from expanding beyond that size.

to learn more about CSS box-sizing property in detail follow this guide and get detailed insights on CSS boarding

Another approach to creating a border inside a

element without increasing its size is to use the box-shadow property with the inset keyword. This method allows you to create a shadow effect that resembles a border inside the element.

Here’s an example of how you can use box-shadow for this purpose:

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;
}

This code snippet adds an inset box shadow with a red color (#f00) and a size of 10px to all sides of the

element, effectively creating a border inside the element.

Please note that this method is supported in modern browsers but may not work in older browsers such as IE 8.

To learn in detail about CSS box shadow, follow this guide.

You can achieve a border inside a <div> element by using the box-shadow property with specific values. For example, to create a bottom border, you can use the following CSS:

div {box-shadow: 0px -3px 0px red inset; }

This code applies an inset box shadow with a red color to the bottom of the <div> element, effectively creating a bottom border. Similarly, for a top border, you can use:

div {box-shadow: 0px 3px 0px red inset; }

This code applies an inset box shadow with a red color to the top of the <div> element, creating a top border effect.