How to change checkbox background color in simple HTML [duplicate]

Checkbox still has light blue color instead needed dark blue color.
asked Nov 13, 2021 at 20:47
427 1 1 gold badge 4 4 silver badges 15 15 bronze badges
5 Answers 5
You can also do something simple in CSS only for the background color so far as I see. I wish there was a simpler way to do the checkmark, you think that would be considered the font color to it but it is not
input[type="checkbox"]
answered Jun 25, 2022 at 22:47
AlThePal78 AlThePal78
863 2 2 gold badges 15 15 silver badges 25 25 bronze badges
accent-color property cannot change the checkmark color. after you set the «desired color» you only can change the background, and the checkmark icon color will automatically follow the desired color
Sep 28 at 22:14
You can’t style the browser’s default checkbox, so we have to hide it and create a custom checkbox like so:
.container < display: block; position: relative; padding-left: 35px; margin-bottom: 12px; cursor: pointer; font-size: 22px; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; >/* Hide the browser's default checkbox */ .container input < position: absolute; opacity: 0; cursor: pointer; height: 0; width: 0; >/* Create a custom checkbox */ .checkmark < position: absolute; top: 0; left: 0; height: 20px; width: 20px; background-color: #fff; border: 2px black solid; >/* On mouse-over, add a grey background color */ .container:hover input ~ .checkmark < background-color: #ccc; >/* When the checkbox is checked, add a blue background */ .container input:checked ~ .checkmark < background-color: #002B4E; >/* Create the checkmark/indicator (hidden when not checked) */ .checkmark:after < content: ""; position: absolute; display: none; >/* Show the checkmark when checked */ .container input:checked ~ .checkmark:after < display: block; >/* Style the checkmark/indicator */ .container .checkmark:after
The “Checkbox Hack” (and things you can do with it)
Then with CSS, you hide the checkbox entirely. Probably by kicking it off the page with absolute positioning or setting its opacity to zero. But just because the checkbox is hidden, clicking the
.control-me < /* Default state */ >#toggle:checked ~ .control-me < /* A toggled state! No JavaScript! */ >
So you can style an element completely differently depending on the state of that checkbox, which you don’t even see. Pretty neat. Let’s look at a bunch of things the “Checkbox Hack” can do. See the Pen
The Checkbox Hack by Chris Coyier (@chriscoyier)
on CodePen. Some of this stuff crosses the line of what you “should” do with CSS and introduces some questionable semantics. It’s still very fun to play with and cool that it’s possible, but in general, functional behavior should be controlled by JavaScript.
Custom Designed Radio Buttons and Checkboxes
- Pioneered by Ryan Seddon
- Similar by Martin Ivanov
- For use on Wufoo forms by me
File system like “tree menu”

The “tabs” design pattern is just toggling on and off of areas, perfect for the checkbox hack. But instead of checkboxes, in which any checkbox can be on or off independently of one another, these tabs use radio buttons in which only one per group can be on at a time (like how only one tab can be active at a time).
A toggle can take the form of ON/OFF, which can be done with a single . Like emoji toggles!
Or it could be multiple elements to switch between differnet distinct values.
Those are radio inputs in this MPG calculator
FAQ Answer Revealing
You’d probably just use a / combo for this these days, but expandable sections can be done with the checkbox hack.
Hide the Sidebar
Like the old school Octopress theme.
Psst! Create a DigitalOcean account and get $200 in free credit for cloud-based hosting and services.
Comments
Mathias Bynens
Permalink to comment # December 21, 2011
The “FAQ Answer Revealing” example is the perfect use case for the HTML5 details / summary elements.
Chris Coyier
Permalink to comment # December 21, 2011
Heck yeah, and with somebody’s jQuery fallback that’s a great choice.
Tim Molendijk
Permalink to comment # December 21, 2011
@Mathias: My initial thought was the same. But then on second though; I don’t think so. How would that work? For browsers that support details / summary , no such thing is needed. For all other browsers, we would need a polyfill script anyway. I’m assuming you’re not suggesting that we manually include a checkbox alongside every details / summary instance, as that would be the worst of both worlds.
Rafał Krupiński
Permalink to comment # December 21, 2011
Nice trick indeed, but semantics suffer 🙂
Andy Griffin
Permalink to comment # December 26, 2011
More suffering: I just used it to make a color picker for a custom blog editor I just made for me. It works beautifully everywhere except iOS. How do I fix it?
Justin Lee
Permalink to comment # December 21, 2011
Like your reference to Soul Coughing in there! Nice!
Permalink to comment # December 21, 2011
Soul Coughing rocks! Very nice!
Maksim Chemerisuk
Permalink to comment # December 21, 2011
I was especially impressed in past by the demo with modal dialogs done by css ninja (take a look here) which uses the same trick.
Thomas Bower
Permalink to comment # December 21, 2011
I made an iOS style on/off toggle using this very technique about a month ago.http://forrst.com/posts/iOS_Pure_CSS_On_Off_switch_Now_with_100_less_i-rMA Worth a check out.
Thomas Bower
Permalink to comment # December 21, 2011
Actually. Scrap that. Different method, but still pretty cool.
Permalink to comment # December 21, 2011
That’s a very bad idea: to use styles like “left: -9999px”. Once you turn direction to rtl there will be large horizontal scroll. Perhaps, it would be there already if someone with system RTL settings such as hebrew, arabian or hindi visits your site—I haven’t tested this.
It’s a much better idea to use styles like “position:absolute;clip:rect(0 0 0 0);” (seen in Lea Verou presentation). “visibility:hidden” is also ok if IE browsers aren’t concerned.
Chris Eagle
Permalink to comment # December 21, 2011
I used the clip method on Whats My MPG for the radio buttons example featured in this post.
Permalink to comment # December 22, 2011
left: -9999px is OK if parent element has overflow: hidden .
visibility:hidden for checkbox is bad idea because then input.checked > label won`t work in IE7/8
Permalink to comment # December 21, 2011
These are great fun! I’d be really interested to read more on people whose opinion is that even playing around with these hacks is bad for the industry. To me, they just seem like a really fun thinking exercise.
Permalink to comment # December 22, 2011
There’s a lot to learn from the CSS part but the HTML part is nonsense: form elements are to be used in forms (*), not in navigation lists, tabs or treelists. Simple questions: where’s the form element? Where’s the submit button?
Advice: if it’s not a form, don’t use form elements. The other “problem” is that CSS Tricks is a successful website with many visitors: Chris Coyer deserves this success but on the other part comes “some” responsibility for beginners and not so beginners that are not sure about their skills and knowledge of good practice.
In my opinion, this is “Stuff you must not do but still can learn from”. Chris added a disclaimer (even huge disclaimers wouldn’t stop few people to copypaste everything they see but it’s their problem) but I still read the title as “This is stuff I can do? OK I’ll do that”. And people like me will complain that “some of this stuff crosses the line” and “some bad semantics” is too vague (I didn’t see good semantics here though, again, there’s a lot to learn from the CSS part).
If you need tabs or a treelist on your site, use JS to hide and show content and check http://hanshillen.github.com/jqtest/ (*) I know that due to limitations in the HTML4.01 recommendation (there isn’t a way to express the fact that an input can be nested in a %block% like p or a fieldset or a fieldstet into a fieldset, etc), many things like a fieldset outside a form are valid but it still doesn’t make sense in a website.
Tim Wright
Permalink to comment # December 22, 2011
I generally agree that inputs shouldn’t be used outside forms, but there’s nothing wrong with using a
Druid of Lûhn
Permalink to comment # December 22, 2011
@Felipe Chris did put a disclaimer there, and people who want to learn can do whatever you want. Nowadays forms are used so much that they could hardly be called that anymore. This is even more of a blogpost than a tutorial anyway.
People can do what they want with what they’ve learned; if you’re working on your own, you technically only have to be as semantic as you need.
Как изменить фон у радиокнопки на CSS

Меня недавно попросили рассказать, как поменять фон у радиокнопки через CSS. Задача это не тривиальная, поскольку обычными путями фон радиокнопки не изменить. Однако, есть обходные пути, о которых я в этой статье и поведаю.
Привожу HTML-код:
Отмечу важную вещь, что обязательно должен быть атрибут id у радиокнопки, плюс for на этот id у тега label. Без этого ничего работать не будет.
.r_button display: none;
>
.r_button + label background: url(«radio.png») no-repeat scroll 0 0;
cursor: pointer;
padding-left: 25px;
>
.r_button:checked + label background: url(«radio_active.png») no-repeat scroll 0 0;
>
Сразу скажу, что «+» означает, что стиль должен быть применён к label, следующему после .r_button.
Теперь поясню, как это работает. Мы скрываем вообще радиокнопку, то есть она не показывается. Зато у label мы ставим поле слева, плюс слева ставим фон неактивной радиокнопки. Однако, мы с Вами поставили for у label. Следовательно, по клику на метке, у нас радиокнопка включается. Следовательно, срабатывает селектор «.r_button:checked + label«, который меняет у нас фон label.
Как только идёт переключение на другую кнопку, сразу возвращаемся к неактивному фону.
Вот таким хитрым образом можно поменять фон у радиокнопки через CSS, а также сделать свой вид «активности«.
Отмечу, что данный способ работает во всех современных браузерах, за исключением IE8 и ниже. Для них придётся писать отдельный файл стилей, в которых оставить стандартные радиокнопки.

![]()
Создано 13.03.2013 04:34:00
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
- Кнопка:
Она выглядит вот так: - Текстовая ссылка:
Она выглядит вот так: Как создать свой сайт - BB-код ссылки для форумов (например, можете поставить её в подписи):