Html select style webkit

problem with and :after with CSS in WebKit

I would like to add some style on a select box with the pseudo :after (to style my select box with 2 parts and without images). Here’s the HTML:

I imagine that this would not, should not be possible, otherwise it would make it too easy to change the contents of forms. Imagine a simple bit of CSS changing the display price for something. It could be shown as cheaper than it really is, tricking people into buying something for more than they expected. (Or course, if someone has access to the CSS of a page/userstylesheet, then they could probably do the same in other ways…)

@Synetech — This is incorrect, the author of the page should have complete control over all aspects of page styling. Browser manufacturers trying to prevent styling of certain elements because they might be used to mislead users is not going to be effective as there are nearly limitless number of ways to trick the system or produce false positives.

11 Answers 11

I haven’t checked this extensively, but I’m under the impression that this isn’t (yet?) possible, due to the way in which select elements are generated by the OS on which the browser runs, rather than the browser itself.

I was looking for the same thing since the background of my select is the same as the arrow color. As previously mentioned, it is impossible yet to add anything using :before or :after on a select element. My solution was to create a wrapper element on which I added the following :before code.

.select-wrapper < position: relative; >.select-wrapper:before

I have used FontAwesome.io for my new arrow, but you can use whatever else you want. Obviously this is not a perfect solution, but depending on your needs it might be enough.

Читайте также:  Java memory allocation exception

This is visually perfect. But you cant click through that icon and select element wont open :/ Any suggestions?

pointer-events: none; should take care of that. There was a problem with my code above. I’ll change any sass above to css to remove any confusion.

This is a great solution but when implementing it I found that for some reason :before worked and NOT :after. I don’t know why.

To my experience it simply does not work, unless you are willing to wrap your in some wrapper. But what you can do instead is to use background image SVG. E.g.

 .archive .options select.opt < -moz-appearance: none; -webkit-appearance: none; padding-right: 1.25EM; appearance: none; position: relative; background-color: transparent; background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' version='1.1' height='10px' width='15px'%3E%3Ctext x='0' y='10' fill='gray'%3E%E2%96%BE%3C/text%3E%3C/svg%3E"); background-repeat: no-repeat; background-size: 1.5EM 1EM; background-position: right center; background-clip: border-box; -moz-background-clip: border-box; -webkit-background-clip: border-box; >.archive .options select.opt::-ms-expand

Just be careful with proper URL-encoding because of IE. You must use charset=utf8 (not just utf8 ), don’t use double-quotes («) to delimit SVG attribute values, use apostrophes (‘) instead to simplify your life. URL-encode s (%3E). In case you havee to print any non-ASCII characters you have to obtain their UTF-8 representation (e.g. BabelMap can help you with that) and then provide that representation in URL-encoded form — e.g. for ▾ ( U+25BE BLACK DOWN-POINTING SMALL TRIANGLE) UTF-8 representation is \xE2\x96\xBE which is %E2%96%BE when URL-encoded.

This is a fantastic, simple, and elegant solution that requires no extra HTML which is exactly what I was looking for! Thanks! This should be the chosen answer IMO.

This is the answer I was looking for. The only issue I’m having is that I can only seem to change the fill to a word like ‘black’ or ‘white’ or ‘gray’. When I try anything like ‘#fff’ or even just #fff it goes away.

What if modifying the markup isn’t an option?

Here’s a solution that has no requirements for a wrapper: it uses an SVG in a background-image. You may need to use an HTML entity decoder to understand how to change the fill colour.

-moz-appearance: none; -webkit-appearance: none; appearance: none; background-image: url('data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22292.4%22%20height%3D%22292.4%22%3E%3Cpath%20fill%3D%22%23000000%22%20d%3D%22M287%2069.4a17.6%2017.6%200%200%200-13-5.4H18.4c-5%200-9.3%201.8-12.9%205.4A17.6%2017.6%200%200%200%200%2082.2c0%205%201.8%209.3%205.4%2012.9l128%20127.9c3.6%203.6%207.8%205.4%2012.8%205.4s9.2-1.8%2012.8-5.4L287%2095c3.5-3.5%205.4-7.8%205.4-12.8%200-5-1.9-9.2-5.5-12.8z%22%2F%3E%3C%2Fsvg%3E'); background-repeat: no-repeat; background-position: right .7em top 50%; background-size: .65em auto; 

Источник

Как оформить раскрывающийся список с помощью только CSS?

Когда-то было довольно сложно оформить элемент для всех браузеров.

Чтобы избежать недостатков, которые были раньше, используйте оформление родительского элемента, добавление псевдоэлементов, а также применение JavaScript.

Оказывается, значительная часть стилей могут создать постоянный и приемлемый блок выбора (selection box) в новых браузерах, лучшим способом сохраняясь в старых браузерах.

Есть множество элементов в блоке выбора, к которым можно применить стиль, в частности width, height, font, border, color, padding, box-shadow и background color.

Рассмотрим пример, где применен стиль:

Пример

html> html> head> title>Заголовок документа title> style> .box < width: 120px; height: 30px; border: 1px solid #999; font-size: 18px; color: #1c87c9; background-color: #eee; border-radius: 5px; box-shadow: 4px 4px #ccc; > style> head> body> p>Обычный блок выбора: p> select> option>Кофе option> option>Чай option> option>Вода option> option selected>Коктейль option> select> p>Оформленный блок выбора: p> select class="box"> option>Кофе option> option>Чай option> option>Вода option> option selected>Коктейль option> select> body> html>

Но стрелка выпадающего (раскрывающегося) списка не меняется. Нет никакого непосредственного способа для ее оформления, но существуют некоторые методы, которые могут быть использованы для изменения стрелки раскрывающегося списка по умолчанию. Давайте рассмотрим эти 3 метода ниже.

1) Используйте appearance: none;

Чтобы скрыть стрелку по умолчанию раскрывающегося списка , установите CSS свойство appearance в значение «none», и дальше добавьте выбранную вами стрелку с помощью сокращенного свойства background.

Заметьте, что свойство appearance все еще считается экспериментальным, и вам потребуется использовать префикс -moz- (для Firefox) и -webkit- (для Chrome, Safari, Opera) для максимальной совместимости браузера.

Пример

html> html> head> title>Заголовок документа title> style> select < width: 140px; height: 35px; padding: 5px 35px 5px 5px; font-size: 18px; border: 2px solid #ccc; -webkit-appearance: none; -moz-appearance: none; appearance: none; background: url("/uploads/media/default/0001/02/f7b4d3d2ba3fe1d8518e6e63d7740e1e73921abf.png") 96% / 15% no-repeat #eee; > select::-ms-expand < display: none; /* удалите стрелку по умолчанию в IE 10 и 11 */ > style> head> body> select> option>Кофе option> option>Чай option> option>Вода option> option selected>Коктейль option> select> body> html>

2) Используйте overflow: hidden;

Сначала вставьте элемент в div контейнер с фиксированной шириной и установите overflow: hidden . Потом для элемента задайте ширину на 20px больше, чем элемент . Таким образом, стрелка раскрывающегося списка будет скрыта (так как для контейнера установлено overflow: hidden ), и теперь уже можно будет применить фоновое изображение с правой стороны .

Пример

html> html> head> title>Заголовок документа title> style> .mystyle select < background: transparent; width: 140px; height: 35px; border: 1px solid #ccc; font-size: 18px; > .mystyle < width: 120px; height: 34px; border: 1px solid #111; border-radius: 3px; overflow: hidden; background: url("/uploads/media/default/0001/02/f7b4d3d2ba3fe1d8518e6e63d7740e1e73921abf.png") 96% / 20% no-repeat #ddd; > style> head> body> div class="mystyle"> select> option>Кофе option> option>Чай option> option>Вода option> option selected>Коктейль option> select> div> body> html>

3) Используйте pointer-events: none;

CSS свойство pointer-events может быть использовано для создания индивидуальных раскрывающихся списков .

Пример

html> html> head> title>Заголовок документа title> style> .mybox < position: relative; display: inline-block; > select < display: inline-block; height: 30px; width: 150px; outline: none; color: #74646e; border: 1px solid #ccc; border-radius: 5px; box-shadow: 1px 1px 2px #999; background: #eee; > /* Select arrow styling */ .mybox .myarrow< width: 23px; height: 28px; position: absolute; display: inline-block; top: 1px; right: 3px; background: url("/uploads/media/default/0001/02/f7b4d3d2ba3fe1d8518e6e63d7740e1e73921abf.png") right / 90% no-repeat #eee; pointer-events: none; > style> head> body> div class="mybox"> span class="myarrow"> span> select> option>Кофе option> option>Чай option> option>Вода option> option selected>Коктейль option> select> div> body> html>

Отличным методом является использование предпочитаемых вами знаков вместо стандартного знака для блока .

Установите знаки с помощью свойства content и установите соответствующий font. Здесь можно установить «Consolas» и «monospace». Потом поверните знак пунктуации, используя свойство transform.

Пример

html> html> head> title>Заголовок документа title> style> select < width: 140px; height: 35px; padding: 4px; border-radius:4px; box-shadow: 2px 2px 8px #999; background: #eee; border: none; outline: none; display: inline-block; -webkit-appearance:none; -moz-appearance: none; appearance: none; cursor: pointer; > label < position: relative; > label:after < content:'<>'; font: 11px "Consolas", monospace; color: #666; -webkit-transform: rotate(90deg); -moz-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); right: 8px; top:2px; padding: 0 0 2px; border-bottom: 1px solid #ddd; position: absolute; pointer-events: none; > label:before < content: ''; right: 6px; top:0px; width: 20px; height: 20px; background: #eee; position: absolute; pointer-events: none; display: block; > style> head> body> label> select> option>Кофе option> option>Чай option> option>Вода option> option selected>Коктейль option> select> label> body> html>

Источник

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