Reputation: 83
I use the code below to create a border around the content background, it looks ok on desktop, but as the screen gets smaller the frame is losing its position and going over the content. Looking for a way to make that frame stick to the background color and be responsive. Here's jsfiddle
<div style="position:relative;">
<div class="bg">
<div>
<h2>Title</h2>
</div>
<div>
<a href="#">View More</a>
</div>
</div>
</div>
body {
background: #000;
}
.bg {
background: #f90000;
padding: 55px 20px;
width: 50%;
margin: 40px auto;
}
.bg h2 {
color: white;
text-align: center;
}
.bg a {
text-align: center;
display: block;
color: white;
font-size: 20px;
}
.bg:after {
content: '';
position: absolute;
top: -15px;
left: 170px;
right: 170px;
bottom: -15px;
border: #fff 1px solid;
}
Upvotes: 0
Views: 278
Reputation: 16855
You have to set position:relative
to the .bg
class and also set min-width
so that the frame should stick for the smaller screens
Upvotes: 1
Reputation: 6587
The problem with your code is that you had fixed values on the left
and right
propreties. That meant that when the window resizes, the width of the backgronud changes, as the relative position of the borders to the window border.
So, to solve the problem use the new CSS3 calc()
function as shown:
body {
background: #000;
}
.bg {
background: #f90000;
padding: 55px 20px;
width: 50%;
margin: 40px auto;
}
.bg h2 {
color: white;
text-align: center;
}
.bg a {
text-align: center;
display: block;
color: white;
font-size: 20px;
}
.bg:after {
content: '';
position: absolute;
top: -15px;
left: calc(25% - 20px); /* Because you padding is 20px */
right: calc(25% - 20px);
bottom: -15px;
border: #fff 1px solid;
}
<div style="position:relative;">
<div class="bg">
<div>
<h2>Title</h2>
</div>
<div>
<a href="#">View More</a>
</div>
</div>
</div>
Upvotes: 0
Reputation: 33870
Your borders (which are in the after
pseudo element) are positioned in absolute but its parent is static (default position
value). Absolute positioned elements are always relative the first none-static parent.
Set .bg
position to relative and change your left and right properties of your :after
so your borders will always be relative to its parent.
body {
background: #000;
}
.bg {
background: #f90000;
padding: 55px 20px;
width: 50%;
margin: 40px auto;
position : relative;
}
.bg h2 {
color: white;
text-align: center;
}
.bg a {
text-align: center;
display: block;
color: white;
font-size: 20px;
}
.bg:after {
content: '';
position: absolute;
top: -15px;
left: -15px;
right: -15px;
bottom: -15px;
border: #fff 1px solid;
}
<div style="position:relative;">
<div class="bg">
<div>
<h2>Title</h2>
</div>
<div>
<a href="#">View More</a>
</div>
</div>
</div>
Upvotes: 1
Reputation:
Make the width, font size, and padding relative to the width.
see: https://www.w3schools.com/cssref/css_units.asp
use the unit vw
Upvotes: 0