user1318054
user1318054

Reputation:

Targeting an active link in CSS

I wrote a custom HtmlHelper to apply...

class = "active"

to a menu item if that is the current page. After viewing the source, I know that this is working correctly, but within my current set-up, I can't seem to target the .active class to apply any styles to it.

Current HTML

<ul id="menu">
    <li>@Html.MenuItem("Home", "Index", "Home")</li>
    <li>@Html.MenuItem("About", "About", "Home")</li>
</ul>

Current CSS

#menu { width: 100%;
      padding: 0;
      margin: 0;
      list-style-type: none;
      padding-top: 6px; }

#menu a { width: 100%;
            font-weight: bold;
            text-decoration: none;
            color: #ffffff;
            padding: 6px 8px 6px 8px;
            text-shadow: 1px 1px 1px #8292a2; }

#menu a:hover { background-color: #e8eff6; color: #2a3744; text-shadow: 1px 1px 1px #e8eff6; }

#menu li { display: inline; }

I am assuming I have a specificity issue going on here, but I can't seem to target the "active" class to apply any type of style to it.

#menu a.active
#menu li a.active

Nothing seems to work. Any ideas?

EDIT: custom HtmlHelper I am using

public static class MenuExtensions
    {
        public static MvcHtmlString MenuItem(
            this HtmlHelper htmlHelper,
            string text,
            string action,
            string controller
        )
        {
            string value;
            var routeData = htmlHelper.ViewContext.RouteData;
            var currentAction = routeData.GetRequiredString("action");
            var currentController = routeData.GetRequiredString("controller");
            if (string.Equals(currentAction, action, StringComparison.OrdinalIgnoreCase) &&
                string.Equals(currentController, controller, StringComparison.OrdinalIgnoreCase))
            {
                value = htmlHelper.ActionLink(text, action, new { controller = controller }, new { @class = "active" }).ToHtmlString();
                return MvcHtmlString.Create(value.ToString());
            }

            value = htmlHelper.ActionLink(text, action, controller).ToHtmlString();
            return MvcHtmlString.Create(value.ToString());
        }
    }

HTML output by viewing source

<ul id="menu">
   <li><a class="active" href="/">Home</a></li>
   <li><a href="/Home/About">About</a></li>
</ul>

As I've said, I know it is working, I just can't seem to target the "active" class even though it exists...

Upvotes: 2

Views: 951

Answers (1)

MarioDS
MarioDS

Reputation: 13063

you put a.active, you should use the ":" like you did with hover. a:active

Edit: after re-reading your question, did you mean a custom css class for menu-items that link to the page the user is currently on? In that case, the way I use ASP, it will automatically take care of those menu items for you. Otherwise, I don't see where you assign that class to your menu items? That is a first problem for sure.

Upvotes: 3

Related Questions