Add an arrow under the active menu item in HTML+CSS

懵懂的女人 提交于 2020-01-02 05:43:31

问题


I am trying to generate a menu like the following:

There are several items in the menu and the active one has an arrow after it. The menu items are tags like the following code:

<div class="menuCenter">
     <div class="linksWrapper">
      <a href="#">Home</a>
      <a class="menuCenterLinkLeft" href="#">Plans & Pricing</a>
      <a class="menuCenterLinkLeft" href="#">Sign In</a>
      <a class="menuCenterLinkLeft active" href="#">Sign Up</a>
      <a class="menuCenterLinkLeft" href="#">Contact</a>
     </div>
</div>

I tryied two options: 1- Absolutely positioning the arrow image with javascript. I have problems when resizing the page. 2- Using the :after pseudo element, like this:

.linksWrapper a.active:after
{
    content: url("images/arrowImg.png");
    position: relative;
    left: -40px;
    top: 30px; 
}

The problem with this approach was the horizontal alignment of the arrow. It should be below the center of the link and I could not achive that. I can use HTML5 or CSS 3.

Any help?


回答1:


Try this:

.linksWrapper a.active:after {
    content: url("images/arrowImg.png");
    position: absolute;
    left: 50%;
    top: 30px;
    margin-left: - <width-of-your-image> / 2; /* negative number!*/
}

sidenote: I avoid putting { on a newline, since it may have nasty effects in javascript.

The trick is left:50%; combined with correcting the position by setting it back half width via margin-left.

See example.




回答2:


The absolute positioning approach should work, you need to put the arrow inside of another div that has position:relative defined, so that the absolute coordinates are relative to this parent div, instead of being relative to the body element.

However, I would go with this approach instead:

Make the arrow a part of the background image of the actual a.active items - this way it will center with background-position and you don't need any scripting!




回答3:


I put this together really quick..

http://jsfiddle.net/8Sqwq/1/

Because I wasn't too sure how flexible your code could be, this is the best I could come up with.

Which ever href has the classname of .active will inherit the arrow

// I updated the fiddle to show it in action.



来源:https://stackoverflow.com/questions/10391343/add-an-arrow-under-the-active-menu-item-in-htmlcss

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!