Как изменить размер checkbox html

Checkboxes in web pages – how to make them bigger?

The standard checkboxes rendered in most browsers are quite small and don’t increase in size even when a larger font is used. What is the best, browser-independent way to display larger checkboxes?

7 Answers 7

In case this can help anyone, here’s simple CSS as a jumping off point. Turns it into a basic rounded square big enough for thumbs with a toggled background color.

input[type='checkbox'] < -webkit-appearance:none; width:30px; height:30px; background:white; border-radius:5px; border:2px solid #555; >input[type='checkbox']:checked

@taylorcressy Except for IE (also IE 11) caniuse.com/#search=Appearance — but worked fine for other browsers. Thanks!

@Paul: Thanks for sharing. I was wondering how you deal with the checkmark showing up. With the background just set to a color, the white checkmark in the box is no longer visible. Is there an easy solution? I’ve tried add a html entity for the check in a :before, but wondering if there is an alternative

Actually there is a way to make them bigger, checkboxes just like anything else (even an iframe like a facebook button).

Wrap them in a «zoomed» element:

It might look a little bit «rescaled» but it works.

Читайте также:  Как php отправляет smtp

Of course you can make that div float:left and put your label besides it, float:left too.

Note that on Firefox (as of version 36), this will result in a very blurry appearance. It scales well in Chrome, though. Demo: jsfiddle.net/tzp858j3

Can’t zoom: 2 and transform: scale(2) be directly applied to the checkbox? Why does it need a wrapper?

Thanks! looks like your code takes more browsers into account then I could ever test with, but it works on everything I’ve tried. Especially nice on my I-phone, where checkboxes just about become dots! BTW, you can put smaller fractional scaling (like 1.5) in the places where this snipet puts «2», and for a medium size checkbox.

Not totally cross-browser (it’s better to set a class in HTML and use the class selector in CSS), but this might be a better solution than mine. +1

I was using width and height for example purposes. Probably a combination of Harmen and my solution is the way to go as you may need more styling than CSS can reasonably provide.

This works on ipad safari where checkboxes often need to be larger to make it easier for users to click.

Major limitation is that it doesn’t work at all in Firefox (as of Firefox 36) and will in fact look quite unnatural (the checkbox is regular sized but padding around it fills the 100 x 100px area.

I tried changing the padding and margin and well as the width and height , and then finally found that if you just increase the scale it’ll work:

I tried a number of these solutions and this was the only one that didn’t cause other issues, also worth noting that scale is very widely supported by browsers so very cross browser compatible. I created a class so I could apply it to only the checkboxes I wanted to, which could be used to scale anything: .scale-up-20

Pure modern 2020 CSS only decision, without blurry scaling or non-handy transforming. And with tick! =)

Works nice in Firefox and Chromium-based browsers.

So, you can rule your checkboxes purely ADAPTIVE, just by setting parent block’s font-size and it will grow with text!

input[type='checkbox'] < -moz-appearance: none; -webkit-appearance: none; appearance: none; vertical-align: middle; outline: none; font-size: inherit; cursor: pointer; width: 1.0em; height: 1.0em; background: white; border-radius: 0.25em; border: 0.125em solid #555; position: relative; >input[type='checkbox']:checked < background: #adf; >input[type='checkbox']:checked:after
   

Here’s a trick that works in most recent browsers (IE9+) as a CSS only solution that can be improved with javascript to support IE8 and below.

Style the label with what you want the checkbox to look like

#checkboxID < position: absolute fixed; margin-right: 2000px; right: 100%; > #checkboxID + label < /* unchecked state */ >#checkboxID:checked + label < /* checked state */ >

For javascript, you’ll be able to add classes to the label to show the state. Also, it would be wise to use the following function:

$('label[for]').live('click', function(e)< $('#' + $(this).attr('for') ).click(); return false; >); 

EDIT to modify #checkboxID styles

Источник

Как изменить размер checkbox html

Как увеличить размер checkbox и radio на CSS

На своей практике я неоднократно сталкивался с тем, что дизайнеры web-сайтов бывают очень далеки от реалий жизни. В результате чего при верстке приходится прилагать немалые усилия, чтобы готовый сайт получился максимально похожим на нарисованный макет. Постоянные читатели блога наверняка читали, как можно разукрасить элементы выбора файлов. Сегодня речь пойдет о чекбоксах и радиокнопках, точнее об их нестандартной стилизации. Много лет назад я уже выкладывал нечто подобное, но там размер чекбокса оставался неизменным, да и решение получилось не самое удачное. Сейчас задача заключается в том, чтобы увеличить кликабельную часть checkbox или radio, и решать я ее буду с помощью современных инструментов, а именно на чистом CSS. Заодно проведу работу над ошибками и сделаю стилизацию элементов так, как должно быть.

Начнем с изменения размера. Вариант с изменением атрибутов width или height отпадает сразу, элементы checkbox или radio это игнорируют или же размер поменяется лишь в некоторых версиях каких-то браузеров. Чуть более продвинутый вариант — это увеличение элемента за счет масштабирования. Например:

Но и это не решение. Хорошо справляется с масштабированием только движок WebKit и браузеры на его основе (Chrome и т.п.), а также последние версии Internet Explorer. Браузеры на базе Mozilla тупо растягивают стандартный чекбокс или кругляш, в результате получается просто вырвиглазный ужас. Но даже если такой фокус удастся, при изменении масштаба все равно придется шаманить с положением модифицированного элемента на странице. Не говоря уже о том, что старые браузеры вообще не поддерживают атрибут transform.

Наиболее правильный вариант решения заключается в использовании дополнительных тегов, которые будут отвечать за размер кликабельной области и при этом менять свои стили в зависимости от состояния связанного с ними элемента. Фрагмент HTML-страницы в этом случае будет выглядеть примерно так:

Как видите, добавился тег span. За счет оборачивания всей этой конструкции в тег label, все его содержимое будет кликабельным, что нам и требуется. Исходный чекбокс надо скрыть, сделав его невидимым через свойство visibility:hidden и установив ему отрицательный отступ. Дополнительный span растягивается до нужных размеров, а его фоновый рисунок, как я уже говорил, меняется в зависимости от состояния элемента. Таблица стилей для такого решения будет следующей:

  1. . big_chk
  2. cursor : pointer ;
  3. >
  4. . big_chk input
  5. padding : 0px ;
  6. margin — right :- 16px ;
  7. visibility : hidden ;
  8. >
  9. . big_chk input + span
  10. display : inline — block ;
  11. width : 32px ;
  12. height : 32px ;
  13. background : url ( ‘sprite.png’ ) left top no — repeat ;
  14. >
  15. . big_chk input : checked + span
  16. background — position : right top ;
  17. >

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

Таким образом можно увеличивать размеры элементов checkbox и radio, делая их любой формы под любой самый вычурный дизайн. Решение получилось кроссбраузерным, поддерживаются даже старые браузеры. Также к плюсам можно отнести то, что все сделано на чистом CSS, не требуется никаких скриптов. Верстка при этом осталась абсолютно валидной и предсказуемой по расположению элементов. Недостаток заключается только в необходимости использовать собственные рисунки элементов, но это также решает задачу стилизации и единообразия внешнего вида страницы под разными браузерами.

Готовый пример стилизованных элементов формы checkbox и radio большого размера вы можете посмотреть на демонстрационной странице.

Источник

How to Set the Checkbox Size with HTML and CSS

A checkbox is displayed as a ticked (checked) square box when enabled. Checkboxes are used to allow a user to select among a number of options. The difference between checkboxes and radio buttons is that you can select all the provided options simultaneously when a checkbox is used, while in the case of radio buttons, only one option can be selected.

In this snippet, we will learn how to to change the size of a checkbox. Here, two methods are presented.

Use the CSS width and height Properties

You can set the checkbox size by using the CSS width and height properties. Use the height property to set the height of the checkbox and the width property to set the width of the checkbox.

Your code will look like this:

input./*checkbox class name*/ < width: /*preferred width*/; height: /*preferred height*/; >

Now let’s see an example to understand how to do it.

Example of setting the size of a checkbox with the width and height properties:

html> html> head> title>Title of the document title> style> input.larger < width: 50px; height: 50px; > style> head> body> h2>Checkbox size example h2> p>Default checkbox size: p> input type="checkbox" name="checkBox1" checked> p>A larger checkbox: p> input type="checkbox" class="larger" name="checkBox2" checked> body> html>

Result

It works well in Google Chrome, Microsoft Edge. But in Mozilla Firefox the clickable checkbox area is as defined, but it shows a default size checkbox.

Use the CSS transform Property

An alternative approach that also works for Mozilla Firefox is to use the CSS transform property. This method works well for Chrome as well.

The code syntax will be like this:

input./*checkbox class name*/ < transform: scale(/*preferred magnification*/); >

There are some disadvantages to using this method. To keep it within the browser window or prevent it from overlapping with other elements, the checkbox should be located accurately. In some browsers, the checkbox can appear pixelated for larger sizes.

Example of setting the size of a checkbox with the transform property:

html> html> head> title>Title of the document title> style> input.larger < transform: scale(5); margin: 30px; > style> head> body> p>Default checkbox size: p> input type="checkbox" name="checkBox1" checked> p>A larger checkbox: p> input type="checkbox" class="larger" name="checkBox2" checked> body> html>

Источник

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