In this article, we will learn how to add a border inside an element using CSS.

Let's say we have two rectangular-shaped div elements on our page. And we want both the box looks the same in its height and in its width with and without a border.

One box has a border of 5px solid black and the other box doesn't have a border.

How to add CSS border inside a div element

As you can see, the rectangular box on the left (box1) looks weird compared to the right one. It is because the border of 5px is added outside the box.

So, how can we fix the issue with the border so that both the div look similar?

Well, the solve this issue we have three solutions in CSS:

  1. Using box-sizing
  2. Using outline property, and
  3. Using box-shadow property

Using box-sizing property to add a border

We can use the box-sizing property in CSS to add a border inside any element on the HTML page.

The box-sizing property lets us include the border and padding in an HTML element's width and height.

So, let's set the box-sizing property to border-box to include the border around the element.

.box1 {
  height: 100px;
  width: 200px;
  background-color: palevioletred;
  border: 5px solid black;
  box-sizing: border-box;
}

Using outline property

We can also use the outline property instead of the border property to add a border inside our div.

Example:

.box1 {
  height: 100px;
  width: 200px;
  background-color: palevioletred;
  outline: 5px solid black;
  outline-offset: -5px;
}

The outline property is a line that is used to define an outline area around an element box.

The outline-offset property is used to add a space between the outline and the border of an element. We have set it to -5px to put it inside the border of the box element.

Result:

Using box-shadow property

Another way to add a border inside an element is using the box-shadow property.

The box-shadow property is used to give a shadow effect around an element frame.

Example:

.box1 {
  height: 100px;
  width: 200px;
  background-color: palevioletred;
  box-shadow: inset 0px 0px 0px 5px black;
}

The inset keyword changes the shadow to one inside the element. So the shadow is above the background of the element and below the content in the element.

Results:

css border inside div

Edit r7w1o9

So, these are the three different ways to add a CSS border inside a div.


💾 Recommended Articles