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
.

https://i.sstatic.net/YBg4f.png

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

Having trouble customizing the active state of a react router navlink using css modules in React?

Objective I am attempting to add styles to the active route in a sidebar using css modules while still maintaining the base styles by assigning 2 classes. This is the code I have tried: <NavLink to={path} className={` ${classes.nav_ ...

Using jQuery's .html() method will remove the selected attribute from the dropdown menu option

When generating HTML dynamically, a select element is included. After choosing an option inside it, everything works fine. For example: <div id="test"> <select> <option value="1">1</option> <option value="2" selec ...

Steps for connecting an external .otf file in p5.js

I'm struggling to connect a custom font file to my p5.js sketch through a URL in order to upload it on codepen.io. Unfortunately, the font is not available on Google Fonts. I attempted to include the URL in the load font function like this: loadFon ...

Animating transitions in a Vuetify data table

I am in the process of animating the data on a Vuetify data table. My objective is to make the current data slide out to the right when Next is clicked, and then have the new data slide in from the left. The current result I am getting can be viewed here: ...

$q.all - successfully resolving some HTTP requests while encountering errors on others

I encountered a coding scenario like this angular.forEach(config.tvshows.shows, function(show) { promises.push($http.get('http://epguides.frecar.no/show/' + show.replace(/\s|\./g, '') + '/next/')); }); re ...

Implementing CodeIgniter's HMVC structure to dynamically update data using AJAX functionality

Recently, I came across an AJAX function in an open-source code that caught my attention. function edit_person(id) { save_method = 'update'; $('#form')[0].reset(); // reset form on modals //Ajax Load data from ajax $.ajax({ ...

5 Creative Techniques for Manipulating Boolean Variables in If Statements

I am receiving a unique custom header value and the values I am getting are accurate. The expected values include: true, false, undefined. However, the response associated with the value: false is incorrect. Code Snippet let deviceStatus = req.headers[ ...

What is the reason that utilizing $("input").first() does not function properly on Google Forms?

While practicing with Selenium, I encountered an issue while using this Google form. Specifically, I found that I couldn't select the first input field by using $("input").first() To confirm this issue, I turned to the web browser (Firefox) console t ...

Using v-model with checkboxes in vue.js: A Step-by-Step Guide

How can I use a checkbox with a v-model in Vue2.js? <input type="checkbox" value="test" :checked="selected"/> I need the value of the checkbox to be test, and I also require two-way binding with the prop named selected, ...

Inquiring about utilizing res.render and invoking functions within an EJS template

Exploring node, I created a practice function in a separate file and imported it to my server.js. With express as my framework, passing the function in the res.render object with a parameter works seamlessly. app.get('/projects', (req, res) => ...

The element you are trying to interact with is currently not visible, therefore it cannot be accessed

Currently, I am working on a small Test Automation project using C# with Selenium WebDriver. I have run into an issue where some WebElements are not visible or have their 'Displayed' property set to 'false'. This prevents me from perfor ...

Sending a XML file from a Vue application to an ASP.NET Core backend using axios

I'm encountering difficulties when trying to upload an xml file using axios to my asp .net server. Below is the code snippet I am using on the vue side to retrieve and upload the xml file: uploadXmlFile(file: any) { const rawFile = new XMLHttpRequ ...

Error Encountered During Global Installation of NodeJS

I'm attempting to create a Node module that, when installed globally with the -g flag, can be run with a single command from the terminal. Although the tutorials I've followed suggest it should be straightforward, I seem to be missing something. ...

Updating JavaScript alert title in Android webview: A guide for developers

I have integrated a web view in my Android application, which contains a button. When the button is clicked, it triggers a JavaScript function that displays an alert box with the title "The page at 'file://' says". I would like to customize this ...

Utilizing AJAX for remote execution of JavaScript code

Suppose there is a JavaScript page located at myaddress/service.js on a server. The code in this .js file looks something like: nsBob = { a: function(someParam) {...perform actions and return result}, b: function() {...perform actions and return result} ...

Protractor Mastery: The Ultimate Guide to Stretching and Replacing Elements

My current form looks like the following: https://i.stack.imgur.com/vl7w1.png I am looking to emulate columns that stretch. I can also change the placement of column headings. I believe I should utilize webdrivers methods for this task, but I'm unsur ...

Using AJAX to update the value of a div by clicking within a PHP loop

I'm currently working on a php page where I want to dynamically change the content of a div when a specific link is clicked. The links are generated through a loop, and I need to pass multiple parameters via the URL. Since the divs are also created wi ...

Executing JavaScript code from an external HTML file

My goal is to create and utilize native web components by defining them as HTML files containing markup, CSS, and Javascript all bundled together in one file, similar to how Vue handles .vue files. These components would be fetched from an external compone ...

Changing tabs will redirect the url

Having an issue with ASP AjaxControlToolkit tabs. I want the URL to change based on the tab selected by the user. Check out the code snippet below: <asp:TabContainer ID="TabContainer1" runat="server" Width="100%" Height="100%"> <asp:TabPanel ...

Is there a more concise method for accepting a collection of interfaces in TypeScript?

Issue I am facing a simplified version of a problem with my model: Here is how my model currently looks: interface Instrument { name: string; // ...more properties shared by all instruments... } interface Guitar extends Instrument { type: &q ...