How to align icon and text perfectly in a Bootstrap 5 Button

I am looking to align icons and text within a modal body:

<div class="modal-body">
    <div class="d-grid gap-2" id="someButtons">
    </div>
</div>

This code snippet demonstrates how I insert buttons dynamically:

testItems.forEach(function ( item ) {
    let btn = document.createElement("a");
    btn.setAttribute("role", "button");
    btn.innerHTML = `<i class="fas fa-plus-circle"></i> ${item}`;
    ["btn", "btn-primary"].forEach(item => btn.classList.add(item)); 
    btnsDiv.appendChild(btn)
});

I also experimented with this approach:

let delBtn = document.createElement("a");
    delBtn.setAttribute("role", "button");
    ["btn", "btn-danger"].forEach(item => delBtn.classList.add(item)); 
    delBtn.innerHTML = `<p class="text-start"><i class="fas fa-minus-circle"></i></p>`
    btnsDiv.appendChild(delBtn)

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

Is it possible to achieve this layout using only Bootstrap 5?

Answer №1

You almost got it with the delete button, but the key is to apply .text-start to the buttons themselves. You can also remove the <p> tags. To adjust the spacing in your desired output image, I've added .me-2 to the icons for a right margin.

let items = ['first', 'second', 'third']
let container = document.getElementById('someButtons')
items.forEach(function(item) {
  let button = document.createElement("a");
  button.setAttribute("role", "button");
  button.innerHTML = `<i class="fas fa-plus-circle me-2"></i> ${item}`;
  ["btn", "btn-primary", "text-start"].forEach(style => button.classList.add(style));
  container.appendChild(button)
});
let deleteButton = document.createElement("a");
deleteButton.setAttribute("role", "button");
["btn", "btn-danger", "text-start"].forEach(style => deleteButton.classList.add(style));
deleteButton.innerHTML = `<i class="fas fa-minus-circle me-2"></i> some text`
container.appendChild(deleteButton)
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e5878a8a919691978495a5d0cbd4cbd5">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
<link href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" rel="stylesheet">


<div class="modal-body">
  <div class="d-grid gap-2" id="someButtons">
  </div>
</div>


<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="284a47475c5b5b5f48596c1912060306">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>

Answer №2

const btnsDiv = document.getElementById("someButtons");
const testItems = ["Hi","Hello"];

testItems.forEach(function ( item ) {
    let btn = document.createElement("a");
    btn.setAttribute("role", "button");
    btn.innerHTML = `<i class="fas fa-plus-circle me-2"></i> ${item}`;
    ["btn", "btn-primary", "text-start"].forEach(item => btn.classList.add(item)); 
    btnsDiv.appendChild(btn);
});
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1b3bebeb5b2b5b3a0bf9cb7849b848b94">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="703235373c3b3c3a29327be060fe06fb0effaa2ee82edac9dc8fd939f9cd76b9ea6b5a5dbd436da96dad681">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<div class="modal-body">
    <div class="d-grid gap-2" id="someButtons">
    </div>
</div>

Answer №3

To enhance the flexibility of your buttons, include the Bootstrap classes d-flex with justify-content-start and align-items-center. This will give your buttons a flex layout and align the content to start within them.

If you organize an object using names as keys, you can create nested objects for different button types and icons. Then, you can iterate through these objects in a loop using for ... in along with Object.keys() and Object.values() methods.

const btnObj = {
  'one': {
    'fa-plus-circle': 'btn-primary'
  },
  'two': {
    'fa-plus-circle': 'btn-primary'
  },
  'three': {
    'fa-plus-circle': 'btn-primary'
  },
  'some text': {
    'fa-minus-circle': 'btn-danger'
  }
}

for (let i in btnObj) {
  let btn = document.createElement("a");
  btn.setAttribute("role", "button");
  btn.innerHTML = `<i class="fas ${Object.keys(btnObj[i])}"></i>&nbsp;${i}`;
  ["btn", `${Object.values(btnObj[i])}`, "d-flex", "justify-content-start", "align-items-center"].forEach(item => btn.classList.add(item));
  document.getElementById('someButtons').appendChild(btn)
};
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a1815150e090e081b0a3a4f544b544a">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
<link href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" rel="stylesheet">


<div class="modal-body">
  <div class="d-grid gap-2" id="someButtons">
  </div>
</div>


<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ea8885859e999e988b9aaadfc4dbc4da">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>

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

A guide on incorporating java.type into your JavaScript code

I've been attempting to utilize the following command in my JavaScript: var file = new Java.type("java.io.File"); Unfortunately, I'm encountering an error: Uncaught ReferenceError: Java is not defined Can anyone provide guidance on how to suc ...

Launch the jQuery Fancybox on a separate webpage

I am facing an issue where I have a link in my index.html page and I need it to open a div located in another page named index2.html, but for some reason, it is not working. This is the code I currently have: Link in index.html <a href="#modal" id="o ...

Having trouble locating the web element within a div popup while utilizing Node.js and WebdriverIO

I need assistance with a seemingly simple task. I am currently learning webdriverjs and attempted to write a short code to register for an account on the FitBit website at URL: www.fitbit.com/signup. After entering my email and password, a popup appears as ...

I am experiencing issues with md-no-focus-style not functioning correctly in my configuration

I have a button that triggers the opening of my navigation bar: https://i.sstatic.net/nMr0i.jpg When I click on it, a hitmarker appears: https://i.sstatic.net/OLQaE.jpg The issue is that even after clicking on a navigation item and transitioning to the ...

Interact with the background of a Bootstrap 5 modal

Currently, I am attempting to develop a modal in Bootstrap 5 without a backdrop that permits interaction with the background of the webpage (e.g., highlighting text or scrolling the page while the modal is displayed). Any assistance on this matter would be ...

The page is not able to be uploaded successfully, receiving a HTTP 200 status

Currently, my application is running in Express and I have a button that sends a POST request to the server. After receiving a 200 OK response, the HTML page is displayed. The issue I am facing is that even though I can see the HTML payload in Firebug, my ...

"Encountering a problem with a function showing an undefined error

Trying to incorporate a slider feature into my application led me to reference this w3schools sample. However, upon loading the page, the images briefly appear before disappearing. Additionally, clicking on the arrow or dots triggers an error stating: U ...

Using Ajax data source to bind Bootstrap dropdown items

I have a Bootstrap dropdown button and I am trying to figure out how to load data when the user clicks on it instead of loading the country list when the page initially loads. Below is my code: <div class="btn-group"> <input class="text-box singl ...

Accessing store in Vue, the getter function returns a value representing whether the user is currently logged

I have the user state stored in my Vue store, but when I try to access it like this: let isLoggedIn = store.getters.isLoggedIn Instead of getting a simple true or false, I see this in the console: ƒ isLoggedIn (state) { return state.user ? true : false ...

How can I modify the color of a hover button?

How can I change the color of a link on hover? The code I tried is not working properly. Below is the CSS snippet I have already added: a:hover {color: red;} ...

Using a Javascript library within an Angular component: A comprehensive guide

I've been working on a Web-Client project that involves visualizing sensor data such as velocity and acceleration within a coordinate system. In order to display this coordinate system, I decided to use the graph.js library from https://github.com/dhu ...

Unable to modify the styles of nested Material UI components

I am currently customizing the styles of the card and cardContent components in material ui. I have implemented them within functional components and am facing an issue with overriding the root style of each component. Specifically, I am struggling to modi ...

Where can I locate a specific child element in this scenario?

Currently, I am exploring the possibilities of integrating AngularJS into my application and have encountered a question regarding the click event implementation. Within my HTML code: <div ng-click='clickMe()' ng-controller='testCtrl&ap ...

Flexslider optimized for mobile devices

I am currently using the Sparkling theme on a Wordpress website. This particular theme utilizes Flexslider within a div at the top of the page. Each slide featured in the slider includes an image, as well as a div containing a post title and excerpt. The ...

Integrating secondary functionality into fullPage and Vue.js

I am encountering an error in VueJS that says app.js:11754Uncaught TypeError: (intermediate value)(intermediate value).bind is not a function. I want to trigger the isLoaded function inside fullPage. I have tried using 'this' binding but it' ...

An error persists in Reactjs when attempting to bind a function that remains undefined

I recently tested this code and everything seems to be working correctly, but the compiler is throwing an error saying 'onDismiss' is undefined. Can someone please assist me with this issue? import React, { Component } from 'react'; c ...

When I click the button, the page goes blank and keeps loading endlessly

http://jsfiddle.net/iansan5653/7EPjH/17/ <head> <script type='text/javascript' src='https://www.google.com/jsapi'></script> <script type="text/javascript"> function chart() { var pressure; ...

``Modeling CSS Classes Using the Adjacent Sibling

As a coding novice, I challenged myself to rebuild my WordPress site using HTML, CSS, and JavaScript. In my quest for the best way to create a responsive navigation bar, I stumbled upon an example on W3Schools. My dilemma lies in how to handle Adjacent Cl ...

What is the best way to display live data to multiple users with React and Firebase?

I'm working on a messaging app that needs to update in real-time. Currently, I have implemented the functionality to log in using Google, post messages, and display them on the screen. However, when another user logs in with a different Google account ...

Why isn't the router returning JSON data?

Why am I not receiving a response from this code? const express = require('express') const mongoose = require('mongoose') const authRouter = require('./authRouter') //importing the router const PORT = process.env.PORT || 3000 ...