Click on menu css

A pure CSS onclick context menu

Context menus are one of those very useful UI widgets that still haven’t reached the HTML spec. There have been attempts, but for now everyone tends to make their own custom implementation.

  • Has no dependencies;
  • Can be triggered with a click/tap on any element;
  • Is fully cross-browser;
  • Doesn’t need JavaScript!

Then look no further. It’s much simpler than you think!

An example

This is done in pure HTML and CSS; the JavaScript is there just to add functionality. Source code below.

The HTML

doge meme

The HTML

The trick here was to add tabindex . This makes the element focusable, so that it can open the menu on click. Note that if the clickable element is a or other interactive content (i.e. any focusable element), then you don’t even need this!

I’ve used a , but you can use any element you like. Just add tabindex=»-1″ to make it focusable, if it isn’t already. You can place the menu anywhere you want in the HTML, as long as you’re able to target it with a CSS selector. Just try not to put a button in a button as that’s invalid HTML, although technically it will still work.

Читайте также:  Язык программирования python обучение школьника

The CSS

How do I make the menu appear next to the mouse cursor?

You’ll need JavaScript, but it’s entirely up to you whether you want to do this. Alternatively you could add position: absolute to the menu and just make it appear below (or next to) the element you clicked — no need for JS in this case! Anyway, this did the trick for me:

I want the menu to close when I click the button again!

If that’s the case, you’ll probably be better off using the old checkbox hack.

A note about accessibility

Accessibility isn’t the main focus of this article, but an important topic nonetheless. Menu items should be navigatable with a keyboard: this requires JS, but it’s not hard to achieve. The W3C has done a lot of work around accessibility and there’s plenty of examples you can refer to on their site: for instance, I think the menu button example is particularly relevant.

What about browser support?

It may not work in some very old browsers, so make sure to test it in the browsers you need to support. This MDN page has some info about what happens to the focus of a button when being clicked/tapped on different platforms. I did some tests myself and it seems to work well everywhere, including IE and mobile browsers.

Update: this blog post received a lot of attention and a few folks reached out to me about an issue, specifically with Safari and Firefox, on both iOS and macOS: the button won’t focus. No worries though, it only affects buttons; other tags will work just fine. You may consider using — the semantic meaning is lost entirely here, so if you really want to use a button, you can always focus it programmatically via JS, but only on Apple devices — for example:

Another issue you may find specific to Apple is that the menu won’t close when tapping outside of it. There’s an easy fix: simply add tabindex=»-1″ to the container or the body tag.

And that’s it! I hope you found this useful. If you spot any issues, please do let me know!

Posted by Simone Vittori Last update: 31st March 2023

Источник

How TO — Clickable Dropdown

Learn how to create a clickable dropdown menu with CSS and JavaScript.

A dropdown menu is a toggleable menu that allows the user to choose one value from a predefined list:

Create a Clickable Dropdown

Create a dropdown menu that appears when the user clicks on a button.

Step 1) Add HTML:

Example

Example Explained

Use any element to open the dropdown menu, e.g. a , or

element.

Use a container element (like ) to create the dropdown menu and add the dropdown links inside it.

Wrap a element around the button and the to position the dropdown menu correctly with CSS.

Step 2) Add CSS:

Example

/* Dropdown Button */
.dropbtn background-color: #3498DB;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
>

/* The container — needed to position the dropdown content */
.dropdown position: relative;
display: inline-block;
>

/* Dropdown Content (Hidden by Default) */
.dropdown-content display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
>

/* Links inside the dropdown */
.dropdown-content a color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
>

/* Change color of dropdown links on hover */
.dropdown-content a:hover

/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */
.show

Example Explained

We have styled the dropdown button with a background-color, padding, hover effect, etc.

The .dropdown class uses position:relative , which is needed when we want the dropdown content to be placed right below the dropdown button (using position:absolute ).

The .dropdown-content class holds the actual dropdown menu. It is hidden by default, and will be displayed on hover (see below). Note the min-width is set to 160px. Feel free to change this. Tip: If you want the width of the dropdown content to be as wide as the dropdown button, set the width to 100% (and overflow:auto to enable scroll on small screens).

Instead of using a border, we have used the box-shadow property to make the dropdown menu look like a «card». We also use z-index to place the dropdown in front of other elements.

Step 3) Add JavaScript:

Example

/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() document.getElementById(«myDropdown»).classList.toggle(«show»);
>

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) if (!event.target.matches(‘.dropbtn’)) var dropdowns = document.getElementsByClassName(«dropdown-content»);
var i;
for (i = 0; i < dropdowns.length; i++) var openDropdown = dropdowns[i];
if (openDropdown.classList.contains(‘show’)) openDropdown.classList.remove(‘show’);
>
>
>
>

Источник

CSS Expandable Menu On Click | Expanding Menu Button

css expandable menu on click

Maybe you have seen menus with an expandable feature. In my opinion, they are very attractive and unique. I have seen these types of the menu bar on some websites. Most people who focus on create a beautiful UI, they use these types of unique things.

Now question is that how we can create a menu with an expandable feature on click. Well, we can create this using only HTML & CSS. The concept is very easy, but you must have coding logic. If you don’t have good logic in coding, then you can’t create new things also after knowledge of coding.

So, Today I am sharing CSS Expandable Menu On Click. In other words, Menu Expands On Button Click. This menu is built-in Pure CSS & HTML, I did not use JavaScript or other libraries. You don’t believe, this menu is based on HTML checkbox and lists. Process and codes to creating it is very easy and understandable.

If you are thinking now how this menu actually is, Then see the preview given below.

Preview Of Expanding Menubar On Button Click

See this video preview to getting an idea of how this menu looks like.

Now you can see this visually. If you like this, then get the source code of its.

CSS Expandable Menu On Click Source Code

Before sharing source code, let’s talk about it. First, I created a checkbox using for creating the button. I converted the checkbox to circle using border-radius: 50%; (get info). I created 3 spans to creating the menu icon, I did not use any external icon pack because this is a pure CSS concept.

Left other things you will understand after getting the codes. For creating this menu you have to create only 3 files, one for HTML & one for CSS . Follow the steps to creating this without any error.

Create an HTML file named ‘index.html‘ and put these codes.

Источник

Выпадающее меню по клику средствами CSS без JavaScript

CSS позволяет реализовать выпадающее меню по клику без JavaScript. Сделать это можно c помощью CSS псевдоклассов :focus, :active, :hover и некоторых маленьких хитростей.

Список с классом «sub-menu» по-умолчанию будет скрыт, и будет появляться при получении фокуса соответствующим пунктом главного меню с классном «main-item».
В итоге мы получим примерно такой css-код:

.sub-menu
display: none;
>
.main-item:focus ~ .sub-menu,
.main-item:active ~ .sub-menu,
.sub-menu:hover
display: block;
>

Вот и все, никакой магии и javascript-а, только ловкость рук и css.

Эта реализация будет работать во всех современных веб-браузерах и в IE7+ (в IE6 не проверялось).

А теперь немного моментов на которые следует обратить внимание:

  • псевдокласс :active используется для того, чтобы данная реализация работала в IE7;
  • атрибут tabindex=’1′ используется для того, чтобы псевдокласс :focus корректно работал в браузерах на движке webkit;
  • селектор .sub-menu:hover нужен для того, чтобы у нас была возможность щёлкнуть по ссылкам внутри выпавшего подменю и оно не спряталось в следствии того, что главный пункт потеряет фокус.

Главная | ▲ | Контакты
Copyright © 24GLO LTD ® 2004-2023. All rights reserved.

Источник

Оцените статью