Creating a wider background color for active nav bar links in CSS - A step-by-step guide

I've been working on customizing a CSS navbar and I've managed to get it to work as desired. However, I'm facing an issue with the active state background color, which seems to be the same width as the text itself. I've spent hours searching for a solution but haven't had any luck so far. Ideally, I'd like the background color to extend slightly beyond the text's width. When I try setting the width property in CSS, it doesn't seem to adjust based on the text width.

My project is built using React and Bootstrap.

The current look can be seen in the image below. As shown, the background color matches the width of the navlink text "about".

https://i.stack.imgur.com/LMmzt.png

How can I achieve some breathing room like in the image below? In that example, there is space between the text ends and the background color.

https://i.stack.imgur.com/g7G7t.png

Below is my JavaScript code for the navigation item:

import React from "react";
import "./NaviBar3.css";

function NaviBar3() {
  return (
    <div className="NaviBarDiv sticky-top">
      <nav className="d-flex flex-wrap justify-content-center py-3 mb-4 border-bottom">
        <a
          href="/"
          className="d-flex align-items-center mb-3 mx-5 me-md-auto text-light text-decoration-none"
          data-to-scrollspy-id="home"
        >
          <span className="fs-2">CM</span>
        </a>

        <a
          href="/"
          className="nav-link fs-5"
          data-to-scrollspy-id="about"
        >
          About
        </a>
        <a
          href="#projects"
          className="nav-link fs-5"
          data-to-scrollspy-id="projects"
        >
          Projects
        </a>
      </nav>
    </div>
  );
}

export default NaviBar3;

This is my CSS code:

.NaviBarDiv {

  background-color: #282c34;
}
.active-scroll-spy {
  height: 4ex;
  background-image: linear-gradient(135deg, #f34079 40%, #fc894d);
  border: none;
  border-radius: 5px;
  font-weight: bold;
  color: white;
  cursor: pointer;
}
.nav-link {
  margin-left: 1em;
  margin-right: 1em;
  display: flex;
  justify-content: center;
  align-items: center;
}

Answer №1

Consider using the "padding" property in your CSS code

.nav-link {
  padding-left: 1em;
  padding-right: 1em;
  display: flex;
  justify-content: center;
  align-items: center;
}

Answer №2

To enhance the appearance of the .active-scroll-spy element, consider applying padding

.active-scroll-spy {
  height: 4ex;
  background-image: linear-gradient(135deg, #f34079 40%, #fc894d);
  border: none;
  border-radius: 5px;
  font-weight: bold;
  color: white;
  cursor: pointer;
  padding: 0.5em 1em; /* Padding added to both left and right sides */
}

Answer №3

After @Mohammad Hasibul Hasan's suggestion, I was able to modify the code and make it work. By adjusting the padding with bootstrap, I finally got the desired result:

import React from "react";
import "./NaviBar3.css";

function NaviBar3() {
  return (
    <div className="NaviBarDiv sticky-top">
      {/* <nav className="d-flex flex-wrap justify-content-center border-bottom"> */}
      <nav className="d-flex flex-wrap justify-content-center py-3 mb-4 border-bottom">
        <a
          href="/"
          className="d-flex align-items-center mb-3 mx-5 me-md-auto text-light text-decoration-none"
          data-to-scrollspy-id="home"
        >
          <span className="fs-2">CM</span>
        </a>

        <a
          href="/"
          className="nav-link fs-5 px-3 pt-1"
          data-to-scrollspy-id="about"
        >
          About
        </a>
        <a
          href="#projects"
          className="nav-link fs-5 px-3 pt-1"
          data-to-scrollspy-id="projects"
        >
          Projects
        </a>
      </nav>
    </div>
  );
}

export default NaviBar3;

The changes have resulted in this updated appearance: https://i.stack.imgur.com/DvFfl.png

Answer №4

To enhance your active link, consider adding padding:

.active-scroll-spy {
  height: 4ex;
  background-image: linear-gradient(135deg, #f34079 40%, #fc894d);
  border: none;
  border-radius: 5px;
  font-weight: bold;
  color: white;
  cursor: pointer;
  padding: 1em;
}

Alternatively, you can incorporate bootstrap's padding utility classes into your classname like this:

className="d-flex active-scroll-spy p-4 align-items-center mb-3 mx-5 me-md-auto text-light text-decoration-none"

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 inline css into your Button component with Material UI

const styleList = { backgroundColor:{ background-color: '#f9a825' } } <Button color='primary' classes={fab:styleList.backgroundColor} variant="fab" aria-label="Checkout"> Click Here </Button> In this scenar ...

Tips for creating a seamless merge from background color to a pristine white hue

Seeking a seamless transition from the background color to white at the top and bottom of the box, similar to the example screenshot. Current look: The top and bottom of the box are filled with the background color until the edge https://i.stack.imgur.com ...

Arranging Material UI tabs on both sides

I'm currently working with Material UI tabs and I'm trying to achieve a layout where some tabs are positioned to the left and others to the right. For instance, if I have 5 tabs, I want 3 on the left and 2 on the right. I've tried placing th ...

Addressing the unresolved problem with mongoose through an axios post: A step-by-step guide

Currently, I am tackling an individual project that involves transferring data from a redux form to an express server via an axios call. Although I have successfully sent the client data to the server using body-parser, I am encountering difficulties with ...

Update the code-behind for the Joomla "submit article" page

After incorporating a new template on my Joomla website, I encountered an issue with the "submit an article" page. The fields in the publishing tab were altered to width: 0px;. Here is how the HTML for the category dropdown appears: <div id="jform_cati ...

Is it possible to integrate a standalone MERN app into an existing website for hosting and deployment?

(I seem to be facing a challenge due to my lack of familiarity with available tools, as my searches haven't yielded much information on this topic.) Imagine I have a MERN project named my-app. When I run the server locally, it functions perfectly - I ...

How can I display a "loading..." message as a temporary placeholder while waiting for my Apexcharts to load?

I've spent a day trying to solve this issue but couldn't find a solution. Any help would be greatly appreciated. Recently, I was working on creating a cryptocurrency tracker in React. I successfully built a table that displays multiple currencie ...

able to move through the content without displaying the scrollbar

I am looking to keep my content able to scroll, but I don't want the scrollbar to be visible. I have written my CSS like this: #content-three{ width:100%; height:100%; position:relative; overflow:hidden; } .block_s{ width:90%; ...

How can we stop the jumping of images in the grid? Is there a way to eliminate the jump effect?

Here is a script I am working with: <script src="http://static.tumblr.com/mviqmwg/XyYn59y3a/jquery.photoset-grid.min.js"></script> <script> $(document).ready(function() { $('.photoset-grid').photose ...

Modifying a single element within a class with Jquery

Is it possible to create a stack of pages on a website using JQuery? I found this image that shows what I'm trying to achieve: image. Instead of applying ID css for each page, I'd like to use JQuery. While researching similar questions, I came ac ...

What steps can I take to ensure my React js Material-UI table is both responsive and evenly spaced?

Currently utilizing the MaterialTable component sourced from material-ui, I've encountered two issues that require resolution. 1. Is there a way to ensure equal spacing of columns? Currently, there seems to be an unnecessary amount of space between t ...

I constantly encounter the error message "Unable to access properties of undefined (reading 'map')"

I am in the process of using Nextjs 13 for developing my front end and I have a requirement to fetch a .json file from a URL and utilize it to populate my website through server side rendering. However, I keep encountering an error saying "Cannot read prop ...

React Checkbox Tree implemented with the Material-UI and Formik libraries. Elevate your ReactJS development with this

Trying to implement a Checkbox tree using Material-UIs Tree with formik for the form (checkboxes). I'm close to achieving it, but facing an issue where clicking on a parent node checkbox should also check its children nodes. Any suggestions on how to ...

How can I dispatch multiple actions simultaneously within a single epic using redux-observable?

I am a newcomer to rxjs/redux observable and have two goals in mind: 1) enhance this epic to follow best practices 2) dispatch two actions from a single epic Many of the examples I've come across assume that the API library will throw an exception ...

Modifying the color of a div based on a specified value using JavaScript

<div id="navigation"> Add your text here </div> <input type="text" id="newColor"><button onclick="modifyColor()">Update</button> <script> function modifyColor(){ var chosenColor = document.getElementB ...

Honing in on JavaScript Media Queries within React

I have been attempting to incorporate the media query concept from a resource I found here in my React project. However, when testing the code snippet below, I encountered the following error: TypeError: isMobile.addListener is not a function function App ...

Tips for resizing the MUI DateCalendar component in a Reactjs application

I have the code to show a calendar using MUI DataCalendar. <LocalizationProvider dateAdapter={AdapterDayjs}> <DateCalendar/> </LocalizationProvider> I am looking for a way to make it larger in size. My attempt to achieve this was by ...

I am encountering an issue where my React application is unable to establish a connection with my Express application when I dockerize them together. Can anyone

Currently tackling a project for my university that involves using a react app for frontend, an express app for backend, and mongodb as the database. Previously, I would launch the express app and react app separately before dockerizing them, and everythin ...

Getting a Next.js error after performing a hard refresh on a page that contains a dynamic query

I have encountered an issue with my Next.js app when I attempt to hard reload it in production mode. The error message I receive is 404 - File or directory not found. Below is the code snippet I am using: import { useRouter } from "next/router"; import ...

Why Changing the Width of a Flexbox Container Doesn't Impact Its Children?

Attempting to use TweenLite to animate the width of the blue sidebar down to zero, however facing an issue where the content breaks outside the parent's bounds. https://i.stack.imgur.com/4rEVr.png It is unusual for this to happen with Flexbox, given ...