Using JavaScript, grammatically add material icons side by side

Looking to dynamically update the contents of a div element by adding two material icons side by side.

To test this, I created a simple fiddle that demonstrates what I am trying to achieve: https://jsfiddle.net/zog20r7n/3/

When attempting to modify line 36, which currently contains:

<i class=\"material-icons \" >account inbox</i>

to:

<i class=\"material-icons md-mine\" >account inbox</i>

The first icon ends up being aligned to the right of the second icon. It also seems like upon clicking the button for the first time, the icons are misaligned on the page and the second one appears centered on a new line.

If anyone can shed some light on why this is happening and provide a solution, it would be greatly appreciated. I've tried adjusting the CSS thinking it might be the cause, but without success so far.

Answer №1

I'm not sure what the correct position should be, but....

Check out the CSS icon below.

.material-icons {
    font-family: 'Material Icons';
    font-weight: normal;
    font-style: normal;
    font-size: 24px;
    line-height: 1;
    letter-spacing: normal;
    text-transform: none;
    display: inline-block;
    white-space: nowrap; 
    word-wrap: normal;
    direction: ltr;
    -webkit-font-feature-settings: 'liga';
    -webkit-font-smoothing: antialiased; 
}

Here's how you can override some of these properties:

.material-icons {
  white-space: disable; 
}

And remove spaces between elements:

width: fit-content

Answer №2

  1. Ensure that when using material icons as an icon font, you follow the convention of using snake_case inside the <i> tag: (

    account box => <i class="material-icons">account_box</i>
    ).

  2. Your implementation of material icons is incorrect.
    Incorrect in terms of being "invalid". There is no icon called account inbox. The valid options are account box, account balance, account balance wallet, and account circle.
    This could be considered the main issue with your code (as it appears cluttered and difficult to understand).

  3. It is not advisable to apply text-align: center to every single element on your page. Adding it to the body suffices and can easily be overridden.

  4. The practice of completely replacing two tags with a version containing a style attribute and a font-size declaration seems unnecessary. It would be more efficient to toggle a class on the parent element and apply the appropriate font-size through CSS.

To sum it up, here is how I would approach it:

$("#testButton").on('click', function() { $('#divContent').toggleClass('largeFonts')});
body {
  text-align: center;
}
@font-face {
  font-family: 'Material Icons';
  font-style: normal;
  font-weight: 400;
  src: url(https://fonts.gstatic.com/s/materialicons/v31/2fcrYFNaTjcS6g4U3t-Y5ZjZjT5FdEJ140U2DJYC3mY.woff2) format('woff2');
}

.material-icons {
  font-family: 'Material Icons';
  display: block;
  color:deepskyblue;
  font-style: normal;
  font-weight: normal;
  font-size: 96px;
  line-height: 1;
  text-transform: none;
  word-wrap: normal;
  direction: ltr;
  -webkit-font-feature-settings: 'liga';
  -webkit-font-smoothing: antialiased;
  transform: scale(.25);
  transition: transform .3s cubic-bezier(.4,0,.2,1)
}
#divContent {
  display: flex;
  align-items: center;
  justify-content: space-evenly;
}
#divContent.largeFonts .material-icons {
  transform: scale(1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="testButton" type="button">Click to test</button>

<div id="divContent">
    <i class="material-icons">account_box</i>
    <i class="material-icons">computer</i>
</div>

I maintained the font-size at 96px for consistency and altered the icon size using transform. This results in smoother transitions (demonstrated), lighter load on the browser (even with multiple animated items), and crucially, ensures a consistent line-height across all states to prevent jumping of elements on the same line or below upon clicking the button.

Remember to use autoprefixing.

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 incorporating background-size and background-position within the background-image url()

My div currently has a background image set with background-image url(), but I am trying to achieve the following look: background-image url('example') cover center Here is my current code: div { background-image: url(example); background- ...

Display an image tag using the site_url() function within PHP brackets

I have a loop in my view that is fetching all the data from the database: <?php foreach($content as $contentRow): ?> <?php echo $contentRow->value; ?> <?php endforeach; ?> This loop works well for HTML strings ...

Tips on adding to Jquery html code while maintaining the current CSS styling

My JavaScript function looks like this: function appendAllQna(qnaList, num){ for (var i in qnaList){ var qnaCom = ""; qnaCom += "<div class='scomment scommentLine'>"; if(qnaList[i].sellerYn == "Y"){ ...

Issue: unrecognized symbol

I encountered an issue that I need help with: When running my code, I received the following error at line 993, column 29 in http://localhost:1810/Titulares/Create?Length=9 0x800a03f6 - JavaScript Runtime Error: Invalid character The problematic code on ...

The navigation bar scrolling based on mouse position lacks smoothness and could use some enhancement

I'm currently working on adjusting the navigation bar based on the mouse position. It seems to be functioning, but I'm facing an issue with smoothing out the animation. When I stop moving the mouse to a certain point, there is a delay i ...

Adjust the parent element to match the width of the child by utilizing the "display: grid" property

edit: I'm uncertain if this is a duplicate issue. My concern is not about the background color extending beyond the container width, but rather about expanding the container to match the size of its child with display: grid. I have updated the example ...

Are there any JS/jQuery plugins available for sliding animations that include slideLeft and slideRight functions, similar to the slideUp and slideDown functions?

Does anyone know of a jQuery/JS plugin that combines fading and sliding effects, specifically with slideLeft and slideRight functions similar to jQuery's slideUp and slideDown? I'm hoping to find something ready-made rather than having to build i ...

Concealing a navigation tab with Angular4 in Typescript: A tutorial

I have successfully implemented 3 tabs in my Angular 4 project. At the moment, I am focusing on working with the first two tabs and planning to tackle the third tab in the near future. To keep things clean and organized, I am looking to use JavaScript/Typ ...

Retrieving the body of a GET request using NodeJS and axios

Let me share my request with you: axios.get(BASE_URI + '/birds/random', {Stuff: "STUFF"}) .then(randBird=>{ const birdData = randBird.data const bird = { age: birdData.age, ...

Resolving cached CSS and JS files through the use of local storage

My customers frequently express frustration over not seeing the improvements I've made to my CSS or JS effects. The issue seems to be related to cached files. Perhaps this code snippet could provide a solution: $(document).ready(function(){ va ...

Using Javascript regex to capture the image name from a CSS file

As I work with JavaScript regex, my goal is to extract the image name and extension as a capture group of CSS properties. Criteria Must start with "url" Followed by brackets Optional quotes inside brackets The location can include path information Must ...

Trigger ExtJS input file event when dialogue window is closed

How can we capture the event when a file is selected in an open dialogue box and the OK button is clicked in extjs? **Off topic, the field does not stretch from its normal width. xtype: 'textfield', fieldLabel: 'New (JPG or ...

Enhance your theme property in Styled Components by incorporating numerous style properties

Currently, I am delving into the world of styled components for a fresh project and exploring the theming capabilities it offers. I am finding it challenging to determine the best practice for adding multiple style properties to a single object, essentiall ...

Angular's Spanning Powers

How can I make a button call different methods when "Select" or "Change" is clicked? <button type="button" class="btn btn-default" *ngIf="!edit" class="btn btn-default"> <span *ngIf="isNullOrUndefined(class?.classForeignId)">Select</spa ...

Can integer values be stored in localStorage similar to JavaScript objects and retrieved without requiring typecasting?

After setting an integer value to a localStorage item: localStorage.setItem('a', 1) and checking its data type: typeof(localStorage.a) "string" it shows as a string. I then typecast it to an int for my purposes: parseInt(localStorage.a) My ...

Aligning two items to the right along the vertical axis, even if they have different heights (Bootstrap

I am facing an issue with aligning two links (one text and one image) to the right and ensuring that the bottom of each is vertically aligned. Currently, they appear like this: (vertically aligned with each others' tops) Here's the relevant HT ...

The process of utilizing variables to form objects in ES6

My ES5 code contains a variable as shown below. var options = { clientId : clientId, keepAlive : keepAlive, clean : clean, reconnectPeriod : reconnectPeriod, will : lastWillMessage }; If I want to convert this to ES6, I can do so by writing ...

Including onMouseUp and onMouseDown events within a JavaScript function

I am experiencing an issue with a div that contains an input image with the ID of "Area-Light". I am attempting to pass the ID of the input image to a function. Although event handlers can be directly added inside the input tag, I prefer to do it within ...

When using Selenium WebDriver to locate an object, an error may occur stating that the result of the xpath expression is "[object Text]" instead of an element as expected

I am currently utilizing Selenium to validate the existence of specific text within a web page. Here is an example of how the HTML appears. <html> <div class="a-content"> <!--!-->==$0 " Text to Locate" <b ...

How is it possible that this React setter is effectively working despite the fact that it is within a stale closure

I've come across this interesting function that I need help understanding. The randomize function seems to be consistent in its behavior despite multiple renders, thanks to being wrapped in a useCallback. Each time the randomize button is clicked, it ...