Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

margin

border

I'm pretty sure someone has asked this question already, but I couldn't find it anywhere on Google or here. 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!

like image 753
Obed Parlapiano Avatar asked Nov 03 '16 11:11

Obed Parlapiano


1 Answers

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>
like image 115
BoltClock Avatar answered Sep 16 '22 20:09

BoltClock