Reputation: 135
I have a DIV nested within another DIV. The parent DIV has a border. The nested DIV matches the overall size of the parent DIV.
By positioning the nested DIV absolutely, and using negative positions, I can get the nested DIV to match the size of the parent DIV but the nested DIV overlaps the border of the parent DIV.
I need the border to still be visible.
The following is one go I had at getting this to work but the nested DIV "covers" the parent DIV's borders:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Border</title>
<style>
:root {
--border-width: 16px;
--neg-border-width: calc(var(--border-width) * -1);;
}
.parent {
position: relative;
width: 360px;
height: 240px;
left: 10px;
top: 10px;
border: var(--border-width) dotted black;
}
.nested {
position: absolute;
top: var(--neg-border-width);
right: var(--neg-border-width);
bottom: var(--neg-border-width);
left: var(--neg-border-width);
background-color: lightblue;
}
</style>
</head>
<body>
<div class="parent">
<div class="nested"></div>
</div>
</html>
I tried setting a z-index, box-sizing... but to no avail.
How can I ensure that the parent DIV's border stays visible?
I thought I'd solved it but I haven't.
I have, say, this:
(Here the nested DIV contains a map, and the parent DIV has a yellow background.) You can see how the map (the nested DIV) does not extend under the parent DIV's border.
Here's what I'm after:
The map (the nested DIV) extends under the parent DIV's border to "fully" cover the parent DIV.
Upvotes: 0
Views: 55
Reputation: 14340
If your content is an image (such as a map) you can achieve your goal using a single element with background-image
.
When you use a background-image
with a dotted border you’ll see that the background is tiled by default, and that the origin point of the tiles is inside the left and top borders. The left image below illustrates this. You can switch off tiling using background-repeat
… the centre image illustrates this.
background-repeat: no-repeat;
We can specify a background-position
to adjust the origin point of the background. Simply adjust the position in the negative direction (on both the horizontal and vertical axes) by the width of the border. The right image illustrates this.
background-position: calc(-1 * var(--border-width)) calc(-1 * var(--border-width));
:root {
--border-width: 16px;
}
body {
margin: 1em;
display: inline-flex;
gap: 1em;
}
.d {
width: 180px;
height: 150px;
border: var(--border-width) dotted red;
box-sizing: border-box;
background: url(https://picsum.photos/id/1072/180/150);
}
.d2, .d3 {
background-repeat: no-repeat;
}
.d3 {
background-position: calc(-1 * var(--border-width)) calc(-1 * var(--border-width));
}
<div class="d d1"></div>
<div class="d d2"></div>
<div class="d d3 corrected"></div>
Upvotes: 0