Designing dynamic SVG elements that maintain uniform stroke widths and rounded edges

I'm currently tackling a project that involves creating SVG shapes with strokes that adjust responsively to the size of their parent container. My aim is for these shapes to consistently fill the width and height of the parent container, and I intend to position them absolutely within the parent element. Moreover, I need to incorporate stroke colors into these shapes.

An issue I've run into pertains to the consistency of stroke widths. Despite setting the stroke width to 1px, at times it appears significantly thicker, possibly exceeding 10px, resulting in distorted shapes.

Here's an illustration of my desired outcome: I applied a 1px stroke width here, but it seems exaggerated. Additionally, the stroke widths on the top, bottom, left, and right appear varied even though they are set at 1px each. How can I introduce a 5px border radius to this path?

body {
   padding: 100px 20px;
}


.parent-container {
    width: 100%;
    height: 400px;
    background: black;
    clip-path: polygon(
      0% 0%,
      95% 0%,
      100% 20%,
      100% 100%,
      5% 100%,
      0% 80%,
      0% 0%
    );
    position: relative;
}


.cta-stroke {
    position: absolute;
    inset: 0px;
    width: 100%;
    height: 100%;
    
}

path {
    stroke-width: 1px;
    stroke: red;
}
<!doctype html>
<html>
<head>
<title>svg shapes</title>
</head>

<body>
<div class="parent-container">
 <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" fill="none" preserveAspectRatio="none" 
  class="cta-stroke">
  <path d="M0 0  L95 0  L100 20 L100 100 L5 100 L0 80 L0 0 Z" />
 </svg>
</div>

</body>
</html>

How can I ensure that SVG shapes with responsive strokes align properly with the size of their parent container and retain consistent stroke width? Furthermore, what steps should I take to introduce rounded corners to these shapes? Any assistance or advice on this matter would be highly appreciated. Thank you!

Answer №1

One valuable tip from an insightful article discussing responsive SVGs is as follows:

When dealing with SVG elements, it's important to note that the default scaling behavior includes thickness adjustments for strokes. While this usually works well, there are scenarios – like diagrams and stroke effects on text outlines – where keeping consistent stroke thickness regardless of size is necessary. This is where the lesser-known vector-effect property comes in, which can be implemented through presentation attributes or CSS.

vector-effect: non-scaling-stroke;

The MDN documentation provides further insight into the purpose of setting this value:

This value alters how an object's stroke is rendered. By using

vector-effect: non-scaling-stroke
, the stroke width remains constant despite transformations applied such as scaling or zooming.

Across various browsers, support for this feature is universally positive.

Below is a preview showcasing the impact of utilizing this property. An SVG square of 20 pixels adorned with a 1 pixel red border is displayed, demonstrating the difference between standard scaling and applying

vector-effect: non-scaling-stroke
.

body {
  background: #888;
  margin: 1em;
}

.d1 {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1em;
}

svg {
  width: 100%;
  background: white;
}

svg rect {
  fill: pink;
  stroke: red;
  stroke-width: 1;
}

svg:last-child rect {
  vector-effect: non-scaling-stroke;
}
<div class="d1">

  <svg viewBox="0 0 22 22">
    <rect x="1" y="1" width="20" height="20"/>
  </svg>

  <svg viewBox="0 0 22 22">
    <rect x="1" y="1" width="20" height="20"/>
  </svg>
  
</div>

Upon testing the code snippet, utilize the full page link to observe its responsiveness.

Corner Roundness

In addressing your query about rounded corners, shapes such as <rect> can have their corners smoothed by specifying the radius using properties like rx and ry. However, unlike <path>, it is not possible to round corners of <polygon> or <polyline>. For more information on implementing rounded corners in SVG, refer to this resource.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Hide custom video controls from view

For a while, I was able to hide the controls on my page using position:absolute; and bottom:-36px, which made them pop up when hovering over the player. Recently, however, I noticed that I can now scroll down to see them. How can I maintain the slide-up ef ...

How to identify generic return type in TypeScript

My goal is to develop a core dialog class that can automatically resolve dialog types and return values based on the input provided. I have made progress in implementing this functionality, but I am facing challenges with handling the return values. Each ...

Have an overlay on a specific area of the webpage while ensuring the remaining sections remain interactive to the user's inputs

Looking for a way to add an overlay in a specific area of a webpage without blocking the other sections? I attempted to use the LightBox feature from primefaces components, but it didn't give me the desired result. I'm struggling to keep the unco ...

How to output a string in jQuery if it includes a certain character?

I need to extract all strings that include a specific word within them, like this: <div> <div> <span> <h3>In Paris (Mark Bartels) worked for about 50 years.</h3> </span> </div> ...

Ever since updating my jQuery version to 3.2.1, my ajax code seems to have stopped functioning properly

My program's ajax functionality was running smoothly with jquery version 1.7, but when I updated to version 3.3.1, the ajax part stopped working. I made sure to attach the ajax portion of my code after updating the jQuery version. In the PHP file, I s ...

Adjust css rotation to direct an element towards a specific point

Looking to rotate a div towards a point using the CSS 3 transform rotate function. Progress so far: View code on JSFiddle $(document).ready(function(){ var scw,sch,scx,scy; calcCenter(); $(window).resize(function() { calcCent ...

Looking to introduce Vue.js into an established SSR website?

Can Vue be used to create components that can be instantiated onto custom tags rendered by a PHP application, similar to "custom elements light"? While mounting the Vue instance onto the page root element seems to work, it appears that Vue uses the entire ...

A Node.js function may not provide a response immediately due to a pending request

Here is a simple upload method using node.js and express.js: upload: function(req, res, next){ // Loop through each uploaded file async.each(req.files.upload, function(file, cb) { async.auto({ // Create new path and unique file ...

What distinguishes the sequence of events when delivering a result versus providing a promise in the .then method?

I've been diving into the world of Promises and I have a question about an example I found on MDN Web Docs which I modified. The original code was a bit surprising, but after some thought, I believe I understood why it behaved that way. The specific ...

Ajax/PHP - unrecognized value in autofill

I have implemented this particular example to execute an ajax data query from a MySQL database, which returns a table. Currently, this setup functions correctly when text is manually entered into the input form. Example: The issue arises with the autocom ...

What is the best way to decrease the font size of every element in the DOM?

Is there a way to decrease the size of all DOM elements by a specific amount? Currently, I am using Bootstrap styles where h5 is set at 14px and I need it to be 12px, and h1 is at 36px when I want it to be 34px, and so forth. I have considered two option ...

Display the number of items that have been filtered as soon as the Mixitup page loads

Currently, I am utilizing MixItUp 3 for sorting and filtering items, with the goal of displaying the count of items within each filter category upon the initial page load. Despite attempting a solution found on SO (mixitup counting visible items on initial ...

Sass - Retain the original class hierarchy

Apologies for the vague title, I couldn't think of a better one. As I compile my scss, this piece of code: .foo { ... &__bar { ... } } transforms into the expected output below: .foo { ... } .foo__bar { ... } However, I actually need it t ...

Exploring the Methods to Monitor Variables in Framework7 Store

Currently, I am in the process of developing my app and have opted to utilize the new built-in store system instead of relying on Vuex. I have a variable that undergoes frequent changes and previously used the following code when working with Vuex: store.w ...

Dynamic Height in React Material-UI Table with Sticky Headers and Multiple Rows

Currently, I am working with React and Material-UI to create a table that needs to have a sticky header for a multi-row table head. The challenge I'm facing is that I don't want to specify a fixed height for the table, but instead have all lines ...

How can I position a div element inside another fixed div element?

I'm working on a layout with a fixed gradient div that contains all my content. However, I want the content to be scrollable instead of fixed. How can I make this happen? Here is the current structure: <body> <div class="wrappe ...

Verifying that utilizing a factory is the most effective method for developing a versatile click count listener

In my quest to enhance the functionality of click events, I have devised a click count factory. This factory creates a clickCountObj to keep track of the number of clicks and implements a new function for capturing click events on a specified element and r ...

Troubleshoot React component re-rendering issue

I'm currently facing a challenging bug that only occurs very sporadically (about once every few dozen attempts). During the render call, I'm determined to gather as much information as possible: I want to understand what triggered the rerender ...

Tips for sending information to a child component from a parent in Vue.js

Is there a way to pass the image url to this vue component? I am moving the code to a separate php file that will contain the <script> tag used by Vue, but it seems like it won't recognize the passed data from a parent component. Vue.component( ...

Choose All Box for Dynamic Tables in AngularJS

Hi everyone, I'm currently working on adding a select-all checkbox to the top of my list of checkboxes using a custom directive. I found some guidance on how to do this in a thread that I came across: https://github.com/lorenzofox3/Smart-Table/issues/ ...