Monkey Raptor

Sunday, November 16, 2014

CSS: Using display: block for Anchor (Link) Element

Anchor or the HTML <a> element is displayed as inline by default. So that if we have link within our paragraph/text, it will seamlessly blend in.

For navigation menu purpose, which consists of links (wrapped in div or ul li or other) we can make the anchors displayed as block elements. By doing that, they will occupy most of the empty space of the parent container.

For instance:

See the Pen Basic menu navigation by Monkey Raptor (@monkeyraptor) on CodePen.

As you can see above, the link occupies the empty space of the container even though the mouse cursor is not on the text of the link.

This will be useful for menu or list of links which is independently displayed outside our paragraph/text.

On another story:
I made that demo because of some (big) sites implement the :hover trigger for expanding menu list. That method won't work on device which depends on finger gestures (tap/swipe).
Well, the dropdown was expanded, if I put my finger on the expander, but the links being expanded couldn't be tapped.

I'd suggest these:
  1. We can expand the navigation links as the default view, nothing's hidden. But, if they're too many then...
  2. Use JavaScript to expand them. The trigger will be the click event. Avoid the :hover (CSS) or hover (JS), mouseenter (JS), etc trigger for mobile view site, for essential navigation.
    Anywho, I've tried using "just" CSS, and I couldn't figure it out. It still needs JavaScript to hold the CSS :active state.
  3. Update: we can also use pure CSS for dropdown. The trigger would be :focus event.
Most of mobile devices built-in browsers support JavaScript (except for Opera Mini browser).

BUT, if you don't want to "waste" your time to find out which works or which doesn't, there are splendid frameworks and libraries you can use, such as:
Bootstrap (CSS and JS), Pure (CSS), Zurb (CSS and JS), and others.
Also, jQuery library for shorter and cross-browser JavaScript coding.

I use Bootstrap frequently. It's flexible to be tinkered and such. The documentation is sweetly written and lots of Q&A we can find online about the features.

This is the pure CSS dropdown navigation. No JavaScript.

See the Pen Basic menu navigation by Monkey Raptor (@monkeyraptor) on CodePen.

The menu collapse is triggered if we click on the outside of the expanded menu parent or inside the expanded menu.
Back to the anchor story
That's about it.
Remember, only override the display property for anchor element which is placed inside a parent container, not for all anchor element.
CSS: Using display: block for Anchor (Link) Element

No comments

Post a Comment

Tell me what you think...