Adjusting margin in CSS for SVGIcon to align with adjacent text elements - a step-by-step guide

Is there a way to set margin-left or margin-right for an Icon component inside a toggle button component (svg+text inside button) in ReactJS using CSS?

https://i.sstatic.net/xQLrK.png https://i.sstatic.net/og4yE.png

I am looking to create space between the icon and button placeholder. Using :first-child and :last-child selectors seem to apply in both scenarios (when icon is on the left I want to apply marginRight, when icon is on the right I want to apply marginLeft).

Any ideas on how this can be achieved using CSS?

Answer №1

Don't forget to assign an ID attribute to the SVG tag if you want to style it using CSS.

Tip: If you're working with React, consider creating a separate component for the button to enhance reusability and maintain a clean codebase.

Check out these resources for more insights:

MDN Docs: SVG and CSS

MDN Docs: SVG style

#btn-icon{
  /* Styling indicators */
  margin: 0 1rem;
  fill: red;
  /* Styling indicators */
  
  /* Add your custom styles here */
  
  /* Add your custom styles here */
}
<button>
Placeholder <svg id="btn-icon" focusable="false" aria-hidden="true" viewBox="0 0 24 24">
<path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM8.5 8c.83 0 1.5.67 1.5 1.5S9.33 11 8.5 11 7 10.33 7 9.5 7.67 8 8.5 8zM12 18c-2.28 0-4.22-1.66-5-4h10c-.78 2.34-2.72 4-5 4zm3.5-7c-.83 0-1.5-.67-1.5-1.5S14.67 8 15.5 8s1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"></path></svg>
</button>

Answer №2

If your initial code snippet was accurate, you won't find any siblings that can be styled using CSS.

Since the text content of your buttons is not selectable with CSS, the SVG icon will be both :last-child and :first-child.

You could try using JavaScript to add classes to your buttons:

let buttons = document.querySelectorAll('button');
buttons.forEach(function(button, i){
  let icon = button.querySelector('svg');
  let siblingLeft = icon.previousSibling.textContent;
  // remove whitespace
  siblingLeft = siblingLeft.replace(/\s/g, "");
  let btnClass = siblingLeft ? 'icon-right' : 'icon-left';
  button.classList.add(btnClass);
});
body{
  font-size:2em;
}

button{
  font-size:inherit;
  background:#f4f4f4;
  border: 1px solid #999;
  padding:0.3em;
}

.icon{
  display:inline-block;
  height:1em;
  margin-left:0.3em;
  margin-right:0.3em;
  position:relative;
  bottom:-0.1em;
  fill: blue;
}


.icon-right svg{
  margin-right:0
}

.icon-left svg{
  margin-left:0;
  fill:orange;
}
<button>
 <svg class="icon icon-inline" focusable="false" aria-hidden="true" viewBox="0 0 24 24">
<path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM8.5 8c.83 0 1.5.67 1.5 1.5S9.33 11 8.5 11 7 10.33 7 9.5 7.67 8 8.5 8zM12 18c-2.28 0-4.22-1.66-5-4h10c-.78 2.34-2.72 4-5 4zm3.5-7c-.83 0-1.5-.67-1.5-1.5S14.67 8 15.5 8s1.5.67 1.5 1.5-.67 1.5-1.5 1.5z" /></svg>Placeholder left
</button>

<button>
Placeholder right<svg class="icon icon-inline" focusable="false" aria-hidden="true" viewBox="0 0 24 24">
<path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM8.5 8c.83 0 1.5.67 1.5 1.5S9.33 11 8.5 11 7 10.33 7 9.5 7.67 8 8.5 8zM12 18c-2.28 0-4.22-1.66-5-4h10c-.78 2.34-2.72 4-5 4zm3.5-7c-.83 0-1.5-.67-1.5-1.5S14.67 8 15.5 8s1.5.67 1.5 1.5-.67 1.5-1.5 1.5z" /></svg>
</button>

I believe your existing UI design in CSS already includes classes for different types of icons or positions. (Make sure to provide an example of your button markup for a more precise answer).

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

Tips for setting discrete mapper style in cytoscapejs?

Currently, I am defining the style of cytoscape.js through CSS and converting it to JSON format using this resource. My goal is to implement a discrete mapper for styling. It's similar to the scenario discussed in How to use a descreteMapper like on c ...

What is the best way to update the content of a div when it is being hovered over?

On my website I am building, there is a division that contains text. When I hover over the division, I want the text to change from "example" to "whatever". I came across a forum discussing this, but I'm having trouble understanding it. Can someone p ...

Next.js application shows 404 errors when trying to access assets within the public directory

I've been struggling to display the favicon for my site (which uses next.js). Despite going through numerous Stack Overflow posts and tutorials, I'm feeling increasingly frustrated. The structure of my project, particularly the public directory, ...

The background image will not repeat to completely cover the height

Click here to view my issue. I have set the background image to repeat the entire height, but it's not behaving as expected. Here is my CSS #wrapper { margin: 0px; padding: 0px; background: url(img02.jpg) repeat-x left top; } I attempt ...

Setting a default value in an AngularJS form for a select dropdown menu

My goal is to develop an angularjs form with two fields - one text input and a select. The default setting should be a blank text input, but the select should have a preset value (the first element on the select list). I am following the guidelines in the ...

Bootstrap arranges checkboxes into three evenly spaced columns and centers them within a form

Having trouble organizing my checkboxes into 3 columns and centering them within the form perfectly. Current layout: Click here for image Desired look: Click here for image HTML: ` <form action="/signup" method="POST" ...

Error in Google Translate API AttributeError

Despite changing the gtoken on googletrans stopped working with error 'NoneType' object has no attribute 'group', I am still encountering the "AttributeError: 'NoneType' object has no attribute 'group'" error. Howeve ...

Strategies for incorporating a design in Next.js

Currently, I'm developing a frontend project using Next.js and Tailwind CSS. I have received a Figma design to incorporate into the project. One of the sections requires me to display a series of steps: https://i.stack.imgur.com/gDmGQ.png Do you hav ...

Encountering issues with Stylus when trying to compile the `@font-face

I'm diving into the world of CSS compilers with Stylus for the first time, and I'm facing an issue with loading Google Web Font URLs correctly. Below is the code snippet causing trouble: @font-face { font-family: 'Roboto'; font-st ...

Display the div with the specific id when it is clicked using jQuery

How can I make one div appear when another div is clicked? Specifically, I want #musicinfo to appear when #music is clicked. Below is the CSS styling for these elements: #music { float:left; height:25px; margin-left:25px; margin-top:25px ...

Encountering an unspecified variable in Sass

I am a beginner in the world of sass and I am trying to incorporate a variable from a file named "_designs.scss" into another file called "_component.scss". Despite my efforts, I keep encountering an "Undefined variable: $grey-light-2" error. I have exhaus ...

Tips for positioning a chat box at the bottom of a v-card's visible area

My goal is to create a chat app using Vuejs 3 and Vuetify 3, but I'm encountering an issue aligning the chatbox with the v-card component. Instead of being positioned at the bottom of the v-card, the chatbox (green) appears at the bottom of the page. ...

Why is the div element within the container not automatically occupying 12 columns, but rather only 1?

I'm struggling to comprehend the bootstrap grid system, as explained in Murach's .Net book. Please take the time to read through the entire post. I am aware of the solution (<div class="col-lg-12">Col x</div> works), but I am curious ...

The issue of the color CSS rule not being applied to the button element when transitioning from disabled to enabled on browsers like Safari 14+ is a common challenge

There seems to be an issue with frontend form validation code affecting the disabled attribute of a submit button within a form. Two different css rules are applied for the enabled and disabled states, including changes in the text color of the button ele ...

Populate your website with both a Bootstrap Popover and Modal for interactive user engagement through hover

Here's the situation: I want to showcase a user's name with a popover that reveals a snippet of their profile information. I've got that part down, where it dynamically generates and displays the popover content as needed. The popover functi ...

dynamic slider using material design components

I'm currently working on building a Slider component in React that can switch between having two values or just one, and then store those values in the component state. The issue I'm facing is that the single value slider doesn't seem to mov ...

Connection to external sources has been deactivated

I am experiencing an issue on my website at . When attempting to click on a link, it seems to be disabled. I suspect this is due to the presence of two images at the end of the navigation bar. Removing these images causes the navigation bar to fall apart, ...

Trouble with passing data from action to reducer in Redux with React Native

As a newcomer to Redux, I'm encountering an issue while trying to make an API call in the Action and pass the data to the reducer. Although I can see the response from the API call, there seems to be a problem with sharing the data correctly with the ...

Ways to soften the edges of a picture by utilizing CSS

I am trying to achieve a feathered effect on the edges of an image within an unordered list that contains 3 list items. Each list item has an image and 3 text-containing divs. I am looking for a CSS-only solution to achieve this effect. Currently, my webs ...

Issue with ngRepeat directive

I'm attempting to display an array in a table Below is the relevant code snippet js: var d = [[ '12:00', 'X-Files', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis non nisi in velit tristique scelerisque. ...