Is it possible to add border outside the margin using CSS?

I will note that there is 1 small hack using Box-Shadows that you can implement.

A box shadow extends beyond the padding of the object. the "Shadow" by default is the exact size of the box, which you can then shift left/right, up/down.

So for instance, i could have a style of: box-shadow : 0 -15px 0 #f7f7f7

which would give me a '15px border" to the top

This is only useful though if you need 1 side have a border, like if you are using bootstrap and you want the text to be at the 'top' of the bootstrap column but want to encase it in a color, you can extend the background color on top using a box shadow.


You won't be able to do this with just the element's box since a box is defined by its border edge, not its margin edge, and having borders outside an element's margin edge would interfere with margin collapse.

You could cheat by creating a pseudo-element with your desired border, but IMO it's more trouble than it's worth. The element itself needs to have a margin value equal to your intended margin amount plus your desired border width, and the pseudo-element needs to be absolutely positioned with the element as its containing block, and extend out of the box by this sum (assuming you don't want the border to eat into the margins):

html {
    background-color: #fff;
}

body {
    float: left;
    background-color: #ccc;
}

div {
    position: relative;
    width: 100px;
    height: 100px;
    background-color: #ff0;
    margin: 30px;
}

div::before {
    content: '';
    position: absolute;
    top: -30px;
    right: -30px;
    bottom: -30px;
    left: -30px;
    border: 5px solid #f00;
}
<div></div>

Furthermore, this falls completely apart once you have more than one such element due to margin collapse — and there is no way around this other than to manually adjust specific margins of specific elements to compensate:

html {
    background-color: #fff;
}

body {
    float: left;
    background-color: #ccc;
}

div {
    position: relative;
    width: 100px;
    height: 100px;
    background-color: #ff0;
    margin: 30px;
}

div::before {
    content: '';
    position: absolute;
    top: -30px;
    right: -30px;
    bottom: -30px;
    left: -30px;
    border: 5px solid #f00;
}
<div></div>
<div></div>
<div></div>

Tags:

Css

Border

Margin