What is the best way to center elements within a Bootstrap dropdown menu that have become misaligned because of varying widths of icons preceding them?

I am currently working on a Bootstrap 4 dropdown menu where the clickable items consist of an icon and short text positioned next to the icon. I attempted to align both the icons and text within each element using a table layout, but it seems that the dropdown-item class in Bootstrap is causing interference with the table structure. You can view the issue in this JSfiddle:

Here is the HTML code:

<div class="dropdown">
  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropdown button
  </button>
  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
    <table class="clickable-rows">
      <tbody>
        <tr class="dropdown-item" data-href="#">
          <th><i class="fa fa-credit-card-alt"></i></th>
          <td>Credit card</td>
        </tr>
        <tr class="dropdown-item" data-href="#">
          <th><i class="fa fa-eur"></i></th>
          <td>Cash</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

Javascript used for making rows clickable:

$( document ).ready(function() {
  $('table.clickable-rows tr').click(function() {
    window.location = $(this).data('href');
  });
});

CSS code for cursor styling:

table.clickable-rows td:hover {
  cursor: pointer;
}

The current alignment is not as desired, and I am looking to have 'Credit card' and 'Cash' aligned according to the red line, while also ensuring the icons are centered in their respective columns. How can I achieve this layout?

Please note that the CSS and JS provided are for functionality purposes and may not directly address the formatting issue. They are included to demonstrate a complete example.

Answer №1

There is plenty of discussion online about why using <table /> to structure your HTML elements is not recommended, so I won't delve into that here.

To solve your issue, simply assign a fixed width to the icons or utilize FontAwesome's .fa-fw fixed width class. FontAwesome icons are centered by default within the i.fa tag.

You no longer need to define cursor: pointer; in CSS, and there's no requirement to use JavaScript to retrieve the data-href since the .dropdown-item now functions as a proper anchor tag.

Check out the JSFiddle demo: https://jsfiddle.net/davidliang2008/6s18j09L/12/

Live demonstration...

<div class="dropdown">
  <button class="btn btn-secondary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown button</button>
  <div class="dropdown-menu">
    <a class="dropdown-item" href="#">
      <i class="fas fa-credit-card fa-fw"></i> Credit card
    </a>
    <a class="dropdown-item" href="#">
      <i class="fas fa-euro-sign fa-fw"></i> Cash
    </a>
  </div>
</div>



<!-- Demo CSS libs -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="35575a5a41464147544575011b001b06">[email protected]</a>/dist/css/bootstrap.min.css" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" rel="stylesheet" />

<!-- Demo jQuery and JS bundle w/ Popper.js -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e0c01011a1d1a1c0f1e2e5a405b405d">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>

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

Answer №2

Here's a neat solution for your issue! Bootstrap provides us with the convenient .fa-fw class to ensure consistency and proper spacing for FontAwesome icons, making it easier to solve your problem.

To implement this, simply use the class like this:

<i class="fa fa-credit-card-alt fa-fw"></i>

Check out the code snippet below:

<table class="clickable-rows">
  <tbody>
    <tr class="dropdown-item" data-href="#">
      <th><i class="fa fa-credit-card-alt fa-fw"></i></th>
      <td>Credit card</td>
    </tr>
    <tr class="dropdown-item" data-href="#">
      <th><i class="fa fa-eur fa-fw"></i></th>
      <td>Cash</td>
    </tr>
  </tbody>
</table>

You can also test it out in the sandbox environment:

Answer №3

this could work as well.

.dropdown-item .fa:before {
    display: inline-block;
    min-width: 35px;
    text-align: center;
}

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 code stops functioning once the identical HTML content is loaded through AJAX

Before you mark my question as a duplicate, I have already attempted the solutions provided by similar issues, but unfortunately none of them have resolved my problem. Here is my specific issue: I am working with a fragment that includes the following inpu ...

Increase the size of images on the same screen with a click using WP Metas

Currently, I am utilizing WP Metaslider for a slideshow/gallery presentation. While it is functioning well, I would like to enhance the user experience by allowing the images in the slider to enlarge within the slide when clicked on, rather than opening in ...

What is causing Safari to block styling for <em> elements in RESET.CSS only?

I am utilizing Eric Meyer's reset.css file, which can be found at this link: Interestingly, my <em> definition in my main stylesheet is working perfectly fine on all browsers except Safari. Somehow, only in Safari, the styling for italics is no ...

Evaluating QUnit Test Cases

How do you write a test method in QUnit for validating functions developed for a form? For example, let's consider a form where the name field should not be left blank. If the validation function looks like this: function validNameCheck(form) { if ...

After incorporating some movement effects into my menu, suddenly none of the buttons were responding

While working on my website and trying to add a close menu button, I encountered an issue where all the menu buttons stopped functioning. Here is the HTML code snippet: <div id="openMenuButton"> <span style= "font-size:30px;cu ...

What could be causing my page to appear at different heights in Safari and Firefox compared to Chrome?

I've been working on www.rootologyhealth.com and I'm stumped by the strange behavior of the Nav Bar on the homepage. It's positioned too high in Safari and Firefox, but appears perfectly in Chrome. Despite my efforts to troubleshoot, I can&a ...

Ways to customize the appearance of the navigation bar when hovering

Is there a way to customize the hover state of a navigation bar? I would like to highlight certain menu items in a different color when they are hovered over, such as making "menu1" stand out. Any help with this would be greatly appreciated! <div cla ...

Dynamic search form technology

My HTML view includes a search form and AJAX code to handle the form request $(document).ready(function() { console.log('Ready'); $('.search-wrapper').on('click', '#find-dates', function(a) { a. ...

Adding and removing/hiding tab-panels in Angular 4 with PrimeNg: A step-by-step guide

I'm currently working on a tabView project with a list of tab-panels. However, I am struggling to find a way to dynamically hide and unhide one of the tab panels based on specific runtime conditions. Does anyone have any suggestions or insights on how ...

Develop a program in Python using Selenium to automate web scraping in a loop

I am looking to create a loop that will allow me to extract the individual time figures for each horse in all eight races from the at the races website. Here is an example of the first race (17:15) out of the eight: from selenium import webdriver from s ...

Conceal a card once verified within a bootstrap modal upon successful AJAX completion

On my delete page, there are multiple posts with a delete button. When the delete button is clicked, a Bootstrap modal opens asking for confirmation "Are you sure you want to delete this post? YES : NO" If the YES button is clicked, the .click(function(e) ...

Bring to life the div that has been clicked

There are three divs labeled as "left", "active", and "right" in my setup: Whenever the left div is clicked, it animates to become active and the previously active one moves into its place. I want this same functionality to apply to the right div as well. ...

Enhance Your NextJs Website with Interactive Tooltips using @tippyjs/react

<Link href="/company/add" > <a title="My New Title" data-toggle='tooltip' className="btn btn-primary">My Link</a> </Link> Trying to integrate a Tippy tooltip component with a Nextjs Link do ...

Tips for preventing a bootstrap modal from being dragged beyond its parent container

I need help figuring out how to prevent my bootstrap modal from being dragged outside of its parent container. Is there a way to constrain the modal within its parent? $(document).ready(function() { ShowValidationResult(); }); function ShowValidation ...

Using CSS to leverage the power of both Grid and Flex simultaneously

Help Needed: CSS Challenge! I'm not a fan of CSS and can't seem to crack this code conundrum. Here's what I want the end result to look like: https://i.sstatic.net/z06qO.png Current Situation: #newOrderControl { border-style: solid ...

Position a Bootstrap 3 division within a central division for ultimate centering

I have written a code snippet that looks like this- html, body, .container-table { height: calc(100% - 50px); } /*Centering a div*/ .container-table { display: table; } .vertical-center-row { display: table-cell; vertical-align: middle; } < ...

Create a way to allow users to download html2canvas with a customized filename

I have a div where I want to use html2canvas to save a PNG file of its content. The issue is that the name of the saved file is static in my code and does not change unless I manually edit it. Is there a way to dynamically set the filename based on user i ...

Tips on how to postpone the loading of an image when utilizing a CSS animation on a different element

I'm currently working on a webpage where I have integrated CSS animations to move images around. When you click on these images, a larger version of the image along with a related paragraph is supposed to appear in its place. Initially, I had set up a ...

CSS issue with highlighting menu items

Recently delving into the world of HTML and CSS, I encountered a tricky issue with my menu. The problem arises when hovering on an element - it should highlight by expanding padding and changing border color. However, for some reason, when I hover on one ...

Steer clear of using grey backgrounds for anchors/links in IE 10

What is the best way to prevent the irritating grey background that appears on anchors in IE 10 when they are clicked? ...