Are there ways to incorporate extra icons into NavMenu in Blazor 8?

I am exploring ways to incorporate extra icons into the NavMenu.razor component of my Blazor version 8 application. In the earlier version, Blazor 7, there was an iconset setup located in wwwroot/css/, which allowed me to include additional icons simply by adding their names in the NavMenu.razor. However, I have noticed that the entire css folder is not present in the new Blazor 8 template.

Currently, there are only three icons defined in the NavMenu.razor.css file, and I am unsure how to include more icons there. As someone who is not well-versed in CSS, I am curious if there is an easy way to obtain new icons similar to how it was done in Blazor 7?

Answer №1

Absolutely, it is definitely possible.
Just keep in mind that doing so could significantly increase the download size for your users.

  1. Within App.razor, insert the following line of code:

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9dfff2f2e9eee9effcedb0f4fef2f3eeddacb3acacb3ae">[email protected]</a>/font/bootstrap-icons.min.css">

  2. In NavMenu.razor, make sure to remove the -nav-menu suffix from the icon names (e.g., use bi-house-door-fill)

  3. Delete the old icons from NavMenu.razor.css file.

  4. Adjust the .bi class within NavMenu.razor.css by adding top: -0.75rem;

The last step addresses aligning the icons quickly, but you may need to further refine the styling of that class as needed.

Answer №2

After receiving feedback from Kurt, I was able to find a solution to my issue with the icons. Instead of using standard icons, I switched to icons from a linked library called Blazorise.Icons.FontAwesome. You can find more information about this library here: .

To implement this change, I modified a navigation point in the code for NavMenu.razor:

<NavLink class="nav-link" href="counter">
    <Icon Name="IconName.Add" IconSize="IconSize.Large" />  @* new *@
    <span style="margin-right:0.8em;"></span> Counter  @* new *@
    @*<span class="bi bi-plus-square-fill-nav-menu" aria-hidden="true"></span> Counter *@   @* old *@
</NavLink>

All available icons can be found in the documentation provided.

While I may not know how to use certain standard icons like the ones included in the template, by utilizing an alternative library, I am able to access a wider range of icons as needed.

Answer №3

If you're interested in learning how to customize Blazor's NavMenu, I detailed the process here.

  1. First step is to select a desired icon from Bootstrap Icon library
  2. Next, copy the SVG code of the chosen icon to your clipboard
  3. Then proceed to URL encode the copied SVG code
  4. Find an existing style like .bi-list-nested-nav-menu in NavMenu.razor.css and duplicate it with a new name
  5. Finally, insert the URL-encoded SVG code after "data:image/svg+xml," within your newly created style

Answer №4

After perusing through MATT'S WORK BLOG (mentioned below), I devised a PowerShell script to accomplish this task efficiently. The script generates an output that can seamlessly fit into a Blazor 8 project. Just specify the Bootstrap icon name (as identified in the [Bootstrap Icon Link][1])

The generated output will be ready for implementation.

Insert the following Generated CSS snippet into your NavMenu.razor.css:

.bi-1-circle-nav-menu {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-1-circle' viewBox='0 0 16 16'%3E  %3Cpath d='M1 8a7 7 0 1 0 14 0A7 7 0 0 0 1 8m15 0A8 8 0 1 1 0 8a8 8 0 0 1 16 0M9.283 4.002V12H7.971V5.338h-.065L6.072 6.656V5.385l1.899-1.383z'/%3E%3C/svg%3E");

}

Embed the following HTML code within your NavMenu.razor:

<div class="nav-item px-3">
<NavLink class="nav-link" href="authorform">
    <span class="bi-1-circle-nav-menu" aria-hidden="true"></span> Dashboard
</NavLink>
function Add-BlazorNavMenuIconFromUrl {
    param(
        # The name of the Bootstrap icon
        [Parameter(Mandatory = $true)]
        [string]$IconName,  
        # SVG file on GitHub
        [Parameter(Mandatory = $false)]
        [string]$MenuItem = "BlazorPageHere",  
        # URL to the SVG file on GitHub or elsewhere
        [Parameter(Mandatory = $false)]
        [string]$BlazorPage = "BlazorPageHere"  

    )

    try {
        # Construct the URL to the SVG file on GitHub
        $Url = "https://raw.githubusercontent.com/twbs/icons/main/icons/$IconName.svg"

        # Download the SVG file content directly
        $response = Invoke-WebRequest -Uri $Url
        $BootstrapSvgHtml = $response.Content

        # Process the SVG HTML
        $encodedSvgHtml = $BootstrapSvgHtml -replace 'currentColor', 'white' `
            -replace '"', "'" `
            -replace '<', '%3C' `
            -replace '>', '%3E' `
            -replace "\r?\n", "" 

        # Extract the SVG name from the URL for class naming
        $svgName = [System.IO.Path]::GetFileNameWithoutExtension($Url)
        $IconClassName = "bi-$($svgName)-nav-menu"

        # Create the CSS rule using StringBuilder
        $cssBuilder = New-Object System.Text.StringBuilder
        [void]$cssBuilder.AppendLine(".$IconClassName {")
        [void]$cssBuilder.AppendLine("`tbackground-image: url(`"data:image/svg+xml,$encodedSvgHtml`");")
        [void]$cssBuilder.AppendLine("}")

        $newCssRule = $cssBuilder.ToString()

        Write-Host "Add the following Generated CSS to your NavMenu.razor.css:" -ForegroundColor Yellow
        Write-Host $newCssRule -ForegroundColor Cyan

        $htmlBuilder = New-Object System.Text.StringBuilder
        [void]$htmlBuilder.AppendLine('<div class="nav-item px-3">')
        [void]$htmlBuilder.AppendLine('    <NavLink class="nav-link" href="' + $BlazorPage + '">')
        [void]$htmlBuilder.AppendLine("        <span class=`"bi $IconClassName`" aria-hidden=`"true`"></span> $MenuItem")
        [void]$htmlBuilder.AppendLine('    </NavLink>')
        [void]$htmlBuilder.AppendLine('</div>')

        $htmlMarkup = $htmlBuilder.ToString()
        
        Write-Host "Add the following HTML to your NavMenu.razor:" -ForegroundColor Yellow
        Write-Host $htmlMarkup -ForegroundColor Green

        $clipboardBuilder = New-Object System.Text.StringBuilder
        [void]$clipboardBuilder.AppendLine($htmlMarkup)
        [void]$clipboardBuilder.AppendLine()
        [void]$clipboardBuilder.AppendLine()
        [void]$clipboardBuilder.AppendLine($newCssRule)

        Set-Clipboard -Value $clipboardBuilder.ToString()
    } catch {
        Write-Error "An error occurred: $_"
    } 
}
# Run the function with command line arguments
if ($args.Count -ne 3) {
    $ScriptName = ($MyInvocation.MyCommand.Name).Replace(".ps1","")
    Write-Host "Usage: $ScriptName <IconName> <MenuItem> <BlazorPage>"
    exit
}
Add-BlazorNavMenuIconFromUrl `
    -IconName $args[0] `
    -MenuItem $args[1] `
    -BlazorPage $args[2]

# Example usage:

    Add-BlazorNavMenuIconFromUrl -IconName "1-circle" -BlazorPage "/dashboard" -MenuItem="User Dashboard"

  [1]: https://icons.getbootstrap.com/

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

The Jquery UI confirmation dialog is working flawlessly on the Fiddle platform, but it is not displaying correctly on the

After testing this code snippet on a fiddle and seeing it work perfectly, I attempted to implement it on my website only to find that there is no border appearing, and the layout appears disorganized. Even after removing all the CSS styles and inspecting ...

Is there a way to replace the default Laravel pagination CSS class with a custom theme CSS class?

Is there a way to update my Laravel pagination CSS to match my theme's CSS? I need help with this adjustment. Here is the HTML for the theme's CSS: <div class="row mt-5"> <div class="col text-center"> ...

The current layout of the div is hindering the ability to switch from vertical scrolling to horizontal scrolling

I'm currently utilizing this scroll converter tool to transform vertical scrolling into horizontal scrolling. However, despite correct script inclusion and initialization, the conversion is not working as expected. It seems like there might be an issu ...

Conceal the browser scrollbars

When I have two DIVs on my webpage that are larger than a browser window, it results in a horizontal scrollbar being displayed. How can I hide this browser scrollbar for the first DIV while still showing it for the second one? For example, if I have two ...

"Toggling a switch alters the appearance following the submission of a form

Recently, I incorporated a switch toggle into my form to help filter products. I followed this guide. However, after submitting the form, the page reloads using ajax and the switch toggles back to its initial style before being toggled again. What could be ...

If padding is included, the width of an element will be affected when using rem

I am facing an issue in my project. Whenever I try to insert a custom font-size at the html level, the red badges get deformed when there is padding (p-6) on the first line of code. Can someone assist me with this problem? I am using Tailwind CSS, but even ...

Adjusting the height of a vertical slider in Vuetify2 is not customizable

I've been trying to adjust the height of a vertical slider in vuetify2, but setting it to "800px" or using style="height:800px" doesn't seem to work as intended. Even though the box within my grid expands, the height of the slider remains unchan ...

Increase ng-grid row height dynamically based on content without any external plugins or reliance on jQuery

I came across a similar question on this topic at Angular ng-grid row height However, none of the solutions provided there meet my requirements. If I use CSS to fix the issue, it impacts the page's responsiveness and disrupts ng-grid's header fu ...

Tips for aligning text to the left instead of the right when it exceeds container width in IE 11

Within the div, there is text with a 5px margin on the right. When the container div narrows, the text overflows from the container and loses the right margin. Is it feasible to maintain this margin on the right side while allowing the text to overflow fro ...

Switch between different table rows

I have here a table that is used for displaying menu and submenu items. It's a mix of PHP (to fetch the menu items and their respective submenus) and HTML. What I am trying to figure out is how to toggle the visibility of only the submenu items under ...

Shade the entire td column in different colors depending on the characteristics of th

I am working with a table and here is the code for it: <table> <thead> <tr> <th style="width: 40%; text-align: center; vertical-align: center;">Nr.<br> crt.</th> <th style="font-weight: bold; wi ...

Drupal 6 encountering an inline AJAX error

Is there a way to add custom inline error messages to a form in Node, including CCK and other elements? I have looked at multiple modules, but none of them seem to offer a complete solution as they lack CCK support, upload support, error messages, etc. ...

I encounter issues with HTML input fields becoming unresponsive whenever I attempt to apply CSS filters in IE8 for stretching the background

When I wanted to stretch a background image on my website so that it always fills the available window area regardless of resolution, I initially used background-size:cover;. Unfortunately, Internet Explorer doesn't seem to support valid CSS, so I had ...

Step by step guide to showcasing images dynamically in user interface

My current project involves displaying a screen with an HTML table and an image. The HTML table is fully dynamic. The Code Working Process When the user loads a page (with a URL), I render an HTML table in different parts as the page loads. I retrieve al ...

The video is not displaying on my website

I recently added a video to my webpage that is 3:48 minutes long. However, even though I have the navigation bar and sound in place, the video does not seem to be displaying properly. Here is an image of how it appears: https://i.stack.imgur.com/HeN41.png ...

Scroll to the end of the main div's horizontal position instead of using offset().left

I'm struggling with an issue in my code. <script type="text/javascript"> $(function() { $('ul.nav a').bind('click',function(event){ var $anchor = $(this); /* ...

Arranging numerous Text elements within a solitary Drag and Drop container with the z-index property

I am facing a challenge with stacking twelve arguments in no particular order on a drag and drop element. The texts overlap each other, making it difficult for the end user to see them clearly when dragging and dropping. Is there a way to stack texts using ...

Why does this CSS ticker only display the first four posts?

Hello, I'm interested in adding a News Ticker to my Rails application. I came across this CSS ticker: I'm facing an issue where it only displays the first four posts. I believe the problem might not be with my data retrieval using the .each loop ...

Has there been a recent issue with FireFox 3 where it fails to clear a float and does not recognize negative margins?

I've been searching online, but haven't come across a definitive answer yet. I'm interested in knowing if there is an issue with Firefox 3 when applying a negative margin to a div that is either clearing a float or containing another floated ...

Strategies for properly formatting a second line indent on lists with background bullets

I've set up an unordered list with bullet points created using FontAwesome, along with a background and border radius for added style. My issue is that I want the second line of text to align below the first one rather than under the bullet point. ...