How to hide a in a menu with CSS?
I’ve realized that Chrome, it seems, will not allow me to hide
I agree with Henesnarfel. If you are already doing a search or some kind of query, you should be able to just populate the ones that you want.
@Henesnarfel There can be good reasons to hide options. For example, I had a page with a select listbox and links to hide or show items marked as inactive. No reason to keep multiple lists or query the server for a new list whenever the user changes that option.
17 Answers 17
For HTML5, you can use the ‘hidden’ attribute.
This is the modern answer. Ideally we’re also setting this to disabled so those browsers that don’t support the HTML5 global hidden attribute will have some visual indication for the user.
Does not work in Safari, Edge, nor IE. Bug for Safari is 10 years old, please help by updating existing patches. Cannot find bug in Edge issue tracker.
You have to implement two methods for hiding. display: none works for FF, but not Chrome or IE. So the second method is wrapping the in a with display: none . FF won’t do it (technically invalid HTML, per the spec) but Chrome and IE will and it will hide the option.
EDIT: Oh yeah, I already implemented this in jQuery:
jQuery.fn.toggleOption = function( show ) < jQuery( this ).toggle( show ); if( show ) < if( jQuery( this ).parent( 'span.toggleOption' ).length ) jQuery( this ).unwrap( ); >else < if( jQuery( this ).parent( 'span.toggleOption' ).length == 0 ) jQuery( this ).wrap( '' ); > >;
EDIT 2: Here’s how you would use this function:
jQuery(selector).toggleOption(true); // show option jQuery(selector).toggleOption(false); // hide option
EDIT 3: Added extra check suggested by @user1521986
This crazy method is the only one that actually worked completely cross-browser and didn’t involve creating a faux-hidden select box hack.
Be careful with this. It seems to work great at first but somewhere along the line it stops. Here’s a little demo: jsfiddle.net/Yb6sk/9
Though this solution does hide the element, any attempt to read the value of the
True, all browsers have different implementations. But one reason browsers cannot strictly implement the standard specs is because there is too much live code out there that doesn’t follow the specs. IMO: If there are no other solutions, then by all means use a hack. But if you can follow the spec and solve your problem, why wouldn’t you? It helps your code to play nice with others and helps to strengthen the spec.
I would suggest that you do not use the solutions that use a wrapper because it isn’t valid HTML, which could cause problems down the road. I think the preferred solution is to actually remove any options that you wish to hide, and restore them as needed. Using jQuery, you’ll only need these 3 functions:
The first function will save the original contents of the select. Just to be safe, you may want to call this function when you load the page.
function setOriginalSelect ($select) < if ($select.data("originalHTML") == undefined) < $select.data("originalHTML", $select.html()); >// If it's already there, don't re-set it >
This next function calls the above function to ensure that the original contents have been saved, and then simply removes the options from the DOM.
function removeOptions ($select, $options)
The last function can be used whenever you want to «reset» back to all the original options.
function restoreOptions ($select) < var ogHTML = $select.data("originalHTML"); if (ogHTML != undefined) < $select.html(ogHTML); >>
Note that all these functions expect that you’re passing in jQuery elements. For example:
// in your search function. var $s = $('select.someClass'); var $optionsThatDontMatchYourSearch= $s.find('options.someOtherClass'); restoreOptions($s); // Make sure you're working with a full deck removeOptions($s, $optionsThatDontMatchYourSearch); // remove options not needed
Стилизация select
Стилизация select на чистом CSS без использования сторонних библиотек или JavaScript кода. А также бонус: рассмотрим как стилизовать select option при помощи JavaScript и jQuery.
Стилизация select
Структура будет стандартной:
Чтобы в select отображаемая строка была одна используем атрибут size со значением 1.
Стилизация для нашего select.
-webkit-appearance: none; -moz-appearance: none; -ms-appearance: none; appearance: none; background: url("path/img.png") no-repeat right center; outline: 0;
В примере выше мы прописали четыре строчки ccs свойства appearance с вендорными префиксами, чтобы свойство работало одинаково во всех браузерах. Что это за свойство читайте ниже.
Вся сложность заключалась лишь в замене стандартной стрелки в прямоугольнике, вместо которой мы реализовали background. Таким образом можно вставить любую картинку. Необходимо лишь подогнать размер при помощи свойства background-size
Appearance CSS
Реализовать нашу задачу помогло css3 свойство appearance.
Данное свойство позволяет изменить вид элемента на: button, checkbox, radio, field, icon и многое другое. В нашем случае мы вообще скрыли элемент, используя none и добавили картинку с помощью background.
Стилизация select option
Для того чтобы стилизовать select option нам потребуется JavaScript. Начнём с HTML и CSS.
.select < display: block; max-width: 215px; width: 100%; position: relative; >.new-select < position: relative; border: 1px solid #ced4da; padding: 10px 15px; cursor: pointer; user-select: none; >.new-select__list < position: absolute; top: 45px; left: 0; border: 1px solid #ced4da; cursor: pointer; width: 100%; z-index: 2; background: #fff; user-select: none; >.new-select__list.on < display: block; >.new-select__item span < display: block; padding: 10px 15px; >.new-select__item span:hover < color: #12b223; >.new-select:after < content: ""; display: block; width: 25px; height: 25px; position: absolute; right: 9px; top: 9px; background: url("path-to-image") no-repeat right center / cover; opacity: 0.6; transition: all .27s ease-in-out; transform: rotate(0deg); >.new-select.on:after
Перед JavaScript-кодом должен быть подключен jQuery.
$(".select").each(function () < const _this = $(this), selectOption = _this.find("option"), selectOptionLength = selectOption.length, selectedOption = selectOption.filter(":selected"), duration = 450; // длительность анимации _this.hide(); _this.wrap(" "); $("", < class: "new-select", text: _this.children("option:disabled").text() >).insertAfter(_this); const selectHead = _this.next(".new-select"); $("", < class: "new-select__list" >).insertAfter(selectHead); const selectList = selectHead.next(".new-select__list"); for (let i = 1; i < selectOptionLength; i++) < $("", < class: "new-select__item", html: $("", < text: selectOption.eq(i).text() >) >) .attr("data-value", selectOption.eq(i).val()) .appendTo(selectList); > const selectItem = selectList.find(".new-select__item"); selectList.slideUp(0); selectHead.on("click", function () < if (!$(this).hasClass("on")) < $(this).addClass("on"); selectList.slideDown(duration); selectItem.on("click", function () < let chooseItem = $(this).data("value"); $("select").val(chooseItem).attr("selected", "selected"); selectHead.text($(this).find("span").text()); selectList.slideUp(duration); selectHead.removeClass("on"); >); > else < $(this).removeClass("on"); selectList.slideUp(duration); >>); >);
Input select
Более простой вариант при помощи input. Данный вариант мне нравится больше.
.select < position: relative; display: block; min-width: 220px; width: 100%; max-width: 400px; margin-bottom: 20px; >.select__head < width: 100%; max-width: 100%; box-shadow: 0 0 4px rgba(0, 0, 0, 0.2); border-radius: 10px; padding: 14px 15px; font-size: 14px; line-height: 18px; color: rgba(66, 67, 72, 0.8); cursor: pointer; >.select__head::after < width: 10px; height: 6px; background: #FFF url('data:image/svg+xml,%3Csvg width="10" height="6" viewBox="0 0 10 6" fill="none" xmlns="http: //www.w3.org/2000/svg"%3E%3Cpath fill-rule="evenodd" clip-rule="evenodd" d="M4.50495 5.78413L0.205241 1.25827C-0.0684138 0.970375 -0.0684138 0.503596 0.205241 0.215836C0.478652 -0.0719461 0.922098 -0.071946 1.19549 0.215837L5.00007 4.22052L8.80452 0.215953C9.07805 -0.0718292 9.52145 -0.0718292 9.79486 0.215953C10.0684 0.503736 10.0684 0.970492 9.79486 1.25839L5.49508 5.78425C5.35831 5.92814 5.17925 6 5.00009 6C4.82085 6 4.64165 5.928 4.50495 5.78413Z" fill="%23ED266A"/%3E%3C/svg%3E%0A') no-repeat center / cover; position: absolute; right: 20px; bottom: 50%; transform: translateY(50%); content: ""; display: block; transition: .2s ease-in; >.select__head.open::after < transform: translateY(50%) rotate(180deg); >.select__list < display: none; position: absolute; top: 100%; left: 0; right: 0; background: #fff; box-shadow: 0 0 4px rgba(0, 0, 0, 0.2); border-radius: 10px; margin-top: 5px; max-height: 205px; overflow-x: hidden; overflow-y: auto; z-index: 100; margin: 0; padding: 0; font-size: 14px; color: #424348; scrollbar-color: dark; scrollbar-width: thin; overscroll-behavior: contain; >.select__list::-webkit-scrollbar < width: 7px; background-color: #F8F9FA; padding: 5px; >.select__list::-webkit-scrollbar-thumb < border-radius: 10px; background-color: #D9D9D9; >.select__list .select__item < position: relative; border-top: 1px solid rgba(224, 229, 231, 0.5); padding: 10px 15px; cursor: pointer; list-style-type: none; >.select__list .select__item:hover
jQuery(($) => < $(".select").on("click", ".select__head", function () < if ($(this).hasClass("open")) < $(this).removeClass("open"); $(this).next().fadeOut(); >else < $(".select__head").removeClass("open"); $(".select__list").fadeOut(); $(this).addClass("open"); $(this).next().fadeIn(); >>); $(".select").on("click", ".select__item", function () < $(".select__head").removeClass("open"); $(this).parent().fadeOut(); $(this).parent().prev().text($(this).text()); $(this).parent().prev().prev().val($(this).text()); >); $(document).click(function (e) < if (!$(e.target).closest(".select").length) < $(".select__head").removeClass("open"); $(".select__list").fadeOut(); >>); >);
Проверка открыт ли select
Будем изменять положение стрелки в зависимости от того открыт или закрыт select.
const select = document.querySelector("select"); select.addEventListener("blur", () => selectEvent()); select.addEventListener("click", () => selectEvent()); selectEvent = (event) => < if (event.type == "click") < if (select.classList.contains("change")) < select.classList.remove("change"); >else < select.classList.add("change"); >> if (event.type == "blur") < select.classList.remove("change"); >>;
Если вам понравилась статья про стилизацию select, рекомендую прочитать про Стилизацию чекбоксов.
Надеюсь, вам понравилась данная информация. Если вам интересна тема web-разработки, то можете следить за выходом новых статей в Telegram.
Статьи из данной категории:
Комментарии ( 5 )
Здравствуйте, спасибо за такой пример и скрипт, но я попробовала его использовать, и заметила недочёты..
1. При загрузке страницы по умолчанию уже должно быть какое-то значение. Это не доработано в скрипте. Мне кажется вот здесь text:
_this.children(‘option:disabled’).text() должно быть не disabled, а
_this.children(‘option:selected’).text()
2. Первый по порядку option считается 0-й, то есть цикл нужно начинать с 0, а не с 1
for (let i = 0; i < selectOptionLength; i++) и т.д..
Иначе в псевдоселект добавляются пункты все, кроме первого
3. Мне кажется, что нужно добавить закрытие псевдоселлекта при клике вне этого блока. Потому, что если селекты расположенны рядом, то могут наезжать друг на друга открытые.
Спасибо!
Здравствуйте, Оксана. Спасибо за выявление недостатков скрипта. Как будет время, обязательно код будет исправлен и улучшен.
Здравствуйте! Подскажите, пожалуйста, в чем может быть причина, что не работает js код для селект нигде кроме хрома и сафари?
если несколько селектов на странице, как сделать что бы был открыт только один? открытый закрывается и открывается по которому кликнули
Options with display:none not hidden in IE
I have multiple options in a select. I have sorted the options and disabled and hidden the duplicate options with jquery. The code works well in chrome and firefox but in IE and safari, the options with display:none are still showing up. Here is the jsfiddle of the code:
Which versions of IE are you having trouble with. I know for a fact that IE8 and earlier have extremely limited ability for styling select boxes.
10 Answers 10
IE doesn’t support style=»display:none;» on tags.
Your only option is to remove them — either as part of the creation of the HTML, or via client-side script.
If somebody still faces this issue, here is my solution, it may be helpfull:
$('select.some-list option[id=someId]').attr('disabled', 'disabled').hide();
This hides the option in all browsers and disables if can’t hide :). To bring back the option do not forget to enable it:
$('select.some-list option[id=someId]').removeAttr('disabled').show();
Does not seem to be working in Edge. Has been reported on MS Dev forum, says to be fixed, but I still have the problem.
You can use detach() and remove() to do this.
Expanding on Zhangjiang Huang’s answer: Pretty much you cache all the options, detach them from the drop-down, then you reattach the ones you want.
Use following Js to hide option tag
$('#selectlist option[value=53]').hide(); $('#selectlist option[value=52]').hide(); $('#selectlist option[value=5443]').hide();
@MJQ, you appear to be waiting for a solution that means that
my 2 cents worth on an «old question», yet still a relevant issue.
protected void Page_Load(object sender, EventArgs e) < if (!IsPostBack) < //load subDropDownList all possible values [with an attribute for filtering] >>
var optionList = null; $(function()< if (!optionList) < optionList = new Array(); $("[id$='subDropDownList'] option").each(function () < optionList.push(); >); > $("[id$='mainDropDownList']").on("change", function (e) ").val(this.value).html(this.text).data("filterid", this.filterID)); >); >); >)
The idea here is on client side I load all values into an array, then on change event of the main select I add only the required options. Hope someone finds this helpful.
The solution by @Gev is good, but the options still appear (even though disabled), so the behaviour is inconsistent across browsers.
You could amend the option tag to something else which stops it appearing, but then you lose any attributes or HTML5 data tags.
The solution I came up with was to wrap any options you want disabled in a different tag (in this case a made up one, which does the job and makes it clear what’s happening).
Starting with example of options also with optional data tags:
To hide the options you don’t want:
$("#myselections > option").each(function () "); > >);
To undo the above on the whole list before hiding different options:
$("#myselections > optionhidden").each(function () < $(this).replaceWith($(this).html()); >);