I've found a weird issue where the rect inside the svg stays the same width as the svg on page load. Resizing the window (causing the svg to resize) doesn't update the width of the rect. Inspecting the element and toggling off/on the height or width then causes the width to update. This issue does not occur in Safari but does occur in Chrome and Firefox.
Is there a more correct way of doing the HTML and CSS to get the effect I need? I essentially want a dashed stroke around the box. I can't use dashed border as the dashes are not wide enough.
.box {
background: black;
min-height: 300px;
padding: 65px;
border-radius: 20px;
position: relative;
max-width: 700px;
margin: auto;
}
svg {
width: calc(100% - 46px);
height: calc(100% - 46px);
fill: none;
stroke: white;
stroke-dasharray: 8px;
position: absolute;
top: 23px;
left: 23px;
pointer-events: none;
}
svg rect {
width: calc(100% - 2px);
height: calc(100% - 2px);
}
<div >
<svg xmlns='http://www.w3.org/2000/svg'>
<rect x='1' y='1' rx='5' />
</svg>
</div>
CodePudding user response:
You can apply border-radius
and padding
properties to the svg and make the inner <rect>
responsive using relative units.
body {
}
*{
box-sizing:border-box
}
.resize {
resize: both;
overflow: auto;
padding: 1em;
border: 1px solid red;
width: 100%;
}
.box{
width: 100%;
height:100%;
}
svg {
display: block;
width: 100%;
height:100%;
padding: 23px;
background: #000;
border-radius: 20px;
overflow:visible;
}
rect {
stroke: white;
stroke-dasharray: 8px;
stroke-width:1px;
}
<div >
<div >
<svg xmlns='http://www.w3.org/2000/svg'>
<rect x='0' y='0' rx='5' width="100%" height="100%" />
</svg>
</div>
</div>
<p>Resize me</p>
overflow:visible
will prevent any stroke clipping.
It is also important to set a box-sizing: border-box
property - otherwise padding will introduce overflows.
This way we don't need any calc()
width/height values, that can cause issues when applied to svg elements (... in some browsers).