Skip to content
Advertisement

Bootstrap 5: align icon and text within Button

I want to align icons and text in a modal body:

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

This is how I add the buttons:

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 tried this:

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)

enter image description here

can I achieve this with bootstrap5 alone?

Advertisement

Answer

You were close with your delete button, .text-start is the key but it should be applied to the buttons. You can also remove the <p>. In the following snippet I have also added .me-2 to the icons to give them some right margin to match the spacing you have in your desired output image.

let testItems = ['one', 'two', 'three']
let btnsDiv = document.getElementById('someButtons')
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)
});
let delBtn = document.createElement("a");
delBtn.setAttribute("role", "button");
["btn", "btn-danger", "text-start"].forEach(item => delBtn.classList.add(item));
delBtn.innerHTML = `<i class="fas fa-minus-circle me-2"></i> some text`
btnsDiv.appendChild(delBtn)
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/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/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement