Obed Marquez Parlapiano Obed Marquez Parlapiano - 1 month ago 7
CSS Question

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

I'm pretty sure someone has asked this question already, but I couldn't find it anywhere on Google or SO. I'm just being curious here as to the limitations of CSS regarding this.

Is it possible to add the border of an element outside the margin using CSS? Basically I want the border to be placed outside of the margin instead of outside the padding.

I understand how the box model works in CSS, for this reason I don't think it's possible to do what I'm asking, however, has anyone found any hacks to go around this?

Thanks!

Answer

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>