Border vs Outline in CSS – A Simple Explanation


Border and outline are two ways to add borders around an element in HTML/CSS.
But they don’t behave the same.
Border respects margins between two elements and never spills out.
On the other hand, an outline doesn’t care about margins — it can overflow and bleed into other elements.
Let us understand this with a simple example:
Here I have created two <div>s box1 and box2 having a space (margin) of 10px between them.
<!doctype html>
<html lang="en">
<head>
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
margin: 10px;
}
.box1 {
outline: 1px solid black;
}
.box2 {
border: 1px solid black;
}
</style>
</head>
<body>
<div class="box1">Box 1 uses outline</div>
<div class="box2">Box 2 uses margin</div>
</body>
</html>
Now, no matter how much I increase the border size in box2, the spacing between the two elements is still maintained.
Here I increased the border size to 50px and space between the two boxes is still maintained.
<style>
* {
margin: 0;
padding: 0;
margin: 10px;
}
.box1 {
outline: 1px solid black;
}
.box2 {
border: 50px solid black; /* Border size increased to 50px */
}
</style>
But when I increase the outline size in box1 to 15px, it simply ignores that 10px space and overflows into box2. (Extra: Yes, 5px bleeds into box2 from box2's upper border)
<style>
* {
margin: 0;
padding: 0;
margin: 10px;
}
.box1 {
outline: 15px solid black; /* Outline size increased to 15px */
}
.box2 {
border: 1px solid black;
}
</style>
Same thing happens when outline-offset property of box1 is increased.
Note: Outline offset simply controls how far the outline is pushed outward or inward from its default position.
<style>
* {
margin: 0;
padding: 0;
margin: 10px;
}
.box1 {
outline: 15px solid black;
outline-offset: 15px;
/* Outline-offset property set to 15px. Default value is 0px. */
}
.box2 {
border: 1px solid black;
}
</style>
That's all. Hope it clears the basic difference border and outline in CSS. I have tried to kept the example as simple and possible.
Thank you :] .
Source (my blog): https://insanelogs.xyz/posts/border-vs-outline-in-css-a-simple-explanation/
Subscribe to my newsletter
Read articles from Insane Logs directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Insane Logs
Insane Logs
Hi, I am Insane. Insanelogs - Log of insane Main website: https://www.insanelogs.xyz Blog website: https://blog.insanelogs.xyz My objective with InsaneLogs is to share knowledge and quick tutorials across different domains of computer science that I learn every day — in a simple and easy-to-understand manner. The goal is to help you get started with a topic quickly, and then dive deeper on your own. I believe it’s always better to have something working or functional first, before reading a ton of theory about it!