CSS를 사용하여 체크박스를 스타일링하는 방법
다음을 사용하여 체크박스를 스타일링하려고 합니다.
<input type="checkbox" style="border:2px dotted #00f;display:block;background:#ff0000;" />
하지만 스타일은 적용되지 않았다.이 확인란에는 기본 스타일이 계속 표시됩니다.어떻게 하면 특정 스타일을 줄 수 있나요?
갱신:
다음 답변은 CSS 3이 널리 보급되기 전의 상황을 나타냅니다.현대 브라우저(Internet Explorer 9 이후 포함)에서는 JavaScript를 사용하지 않고 원하는 스타일링으로 체크박스를 치환하는 것이 보다 간단합니다.
다음은 유용한 링크입니다.
- CSS만으로 커스텀폼체크박스 작성
- Easy CSS 체크박스 생성기
- 체크박스 해킹으로 할 수 있는 일
- CSS3에서의 커스텀체크박스와 무선 버튼의 실장
- CSS를 사용한 체크박스의 스타일링 방법
근본적인 문제가 변하지 않았다는 것을 주목할 필요가 있다.여전히 확인란 요소에 스타일(보더 등)을 직접 적용할 수 없으며 이러한 스타일이 HTML 확인란 표시에 영향을 미칩니다.그러나 달라진 점은 CSS만 사용하여 실제 체크박스를 숨기고 자신의 스타일 요소로 대체할 수 있다는 것입니다.CSS는 하게 지원되고 때문에 CSS는 널리 지원되고 있습니다.:checked실렉터에서는, 체크 박스의 상태를 올바르게 반영하도록 교환할 수 있습니다.
오래된 답변
여기 스타일링 체크박스에 대한 유용한 기사가 있습니다.기본적으로 브라우저마다 크게 다르며, 사용자가 어떤 스타일을 선택하든 많은 브라우저가 항상 기본 체크박스를 표시한다는 것을 알게 되었습니다.그래서 정말 쉬운 방법이 없다.
JavaScript를 사용하여 체크박스에 이미지를 오버레이하고 해당 이미지를 클릭하면 실제 체크박스가 켜지는 회피책을 상상하는 것은 어렵지 않습니다.JavaScript가 없는 사용자에게는 기본 체크박스가 표시됩니다.
추가 편집: 이 작업을 수행하는 좋은 스크립트가 있습니다.실제 체크박스 요소를 숨기고 스타일 지정 범위로 대체하며 클릭 이벤트를 리디렉션합니다.
새로운 기능을 사용하여 매우 쿨한 커스텀체크박스 효과를 얻을 수 있습니다.:after ★★★★★★★★★★★★★★★★★」:before체크박스만 수 이 방법의 장점은 DOM에 아무것도 추가할 필요가 없다는 것입니다.단, 표준 체크 박스만 있으면 됩니다.
이 기능은 호환성이 있는 브라우저에서만 작동합니다.할 수 합니다.:after ★★★★★★★★★★★★★★★★★」:before입력 요소에 있습니다.유감스럽게도 현재로서는 WebKit 브라우저만 지원됩니다.Firefox + Internet Explorer 。이 체크박스는 나중에 변경될 것입니다(코드는 벤더 프리픽스를 사용하지 않습니다).
이것은 WebKit 브라우저만의 솔루션(Chrome, Safari, 모바일 브라우저)입니다.
$(function() {
$('input').change(function() {
$('div').html(Math.random());
});
});
/* Main Classes */
.myinput[type="checkbox"]:before {
position: relative;
display: block;
width: 11px;
height: 11px;
border: 1px solid #808080;
content: "";
background: #FFF;
}
.myinput[type="checkbox"]:after {
position: relative;
display: block;
left: 2px;
top: -11px;
width: 7px;
height: 7px;
border-width: 1px;
border-style: solid;
border-color: #B3B3B3 #dcddde #dcddde #B3B3B3;
content: "";
background-image: linear-gradient(135deg, #B1B6BE 0%, #FFF 100%);
background-repeat: no-repeat;
background-position: center;
}
.myinput[type="checkbox"]:checked:after {
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAQAAABuW59YAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAAB2SURBVHjaAGkAlv8A3QDyAP0A/QD+Dam3W+kCAAD8APYAAgTVZaZCGwwA5wr0AvcA+Dh+7UX/x24AqK3Wg/8nt6w4/5q71wAAVP9g/7rTXf9n/+9N+AAAtpJa/zf/S//DhP8H/wAA4gzWj2P4lsf0JP0A/wADAHB0Ngka6UmKAAAAAElFTkSuQmCC'), linear-gradient(135deg, #B1B6BE 0%, #FFF 100%);
}
.myinput[type="checkbox"]:disabled:after {
-webkit-filter: opacity(0.4);
}
.myinput[type="checkbox"]:not(:disabled):checked:hover:after {
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAQAAABuW59YAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAAB2SURBVHjaAGkAlv8A3QDyAP0A/QD+Dam3W+kCAAD8APYAAgTVZaZCGwwA5wr0AvcA+Dh+7UX/x24AqK3Wg/8nt6w4/5q71wAAVP9g/7rTXf9n/+9N+AAAtpJa/zf/S//DhP8H/wAA4gzWj2P4lsf0JP0A/wADAHB0Ngka6UmKAAAAAElFTkSuQmCC'), linear-gradient(135deg, #8BB0C2 0%, #FFF 100%);
}
.myinput[type="checkbox"]:not(:disabled):hover:after {
background-image: linear-gradient(135deg, #8BB0C2 0%, #FFF 100%);
border-color: #85A9BB #92C2DA #92C2DA #85A9BB;
}
.myinput[type="checkbox"]:not(:disabled):hover:before {
border-color: #3D7591;
}
/* Large checkboxes */
.myinput.large {
height: 22px;
width: 22px;
}
.myinput.large[type="checkbox"]:before {
width: 20px;
height: 20px;
}
.myinput.large[type="checkbox"]:after {
top: -20px;
width: 16px;
height: 16px;
}
/* Custom checkbox */
.myinput.large.custom[type="checkbox"]:checked:after {
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGHRFWHRBdXRob3IAbWluZWNyYWZ0aW5mby5jb23fZidLAAAAk0lEQVQ4y2P4//8/AyUYwcAD+OzN/oMwshjRBoA0Gr8+DcbIhhBlAEyz+qZZ/7WPryHNAGTNMOxpJvo/w0/uP0kGgGwGaZbrKgfTGnLc/0nyAgiDbEY2BCRGdCDCnA2yGeYVog0Aae5MV4c7Gzk6CRqAbDM2w/EaQEgzXgPQnU2SAcTYjNMAYm3GaQCxNuM0gFwMAPUKd8XyBVDcAAAAAElFTkSuQmCC'), linear-gradient(135deg, #B1B6BE 0%, #FFF 100%);
}
.myinput.large.custom[type="checkbox"]:not(:disabled):checked:hover:after {
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGHRFWHRBdXRob3IAbWluZWNyYWZ0aW5mby5jb23fZidLAAAAk0lEQVQ4y2P4//8/AyUYwcAD+OzN/oMwshjRBoA0Gr8+DcbIhhBlAEyz+qZZ/7WPryHNAGTNMOxpJvo/w0/uP0kGgGwGaZbrKgfTGnLc/0nyAgiDbEY2BCRGdCDCnA2yGeYVog0Aae5MV4c7Gzk6CRqAbDM2w/EaQEgzXgPQnU2SAcTYjNMAYm3GaQCxNuM0gFwMAPUKd8XyBVDcAAAAAElFTkSuQmCC'), linear-gradient(135deg, #8BB0C2 0%, #FFF 100%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:100%">
<tr>
<td>Normal:</td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" checked="checked" /></td>
<td><input type="checkbox" disabled="disabled" /></td>
<td><input type="checkbox" disabled="disabled" checked="checked" /></td>
</tr>
<tr>
<td>Small:</td>
<td><input type="checkbox" class="myinput" /></td>
<td><input type="checkbox" checked="checked" class="myinput" /></td>
<td><input type="checkbox" disabled="disabled" class="myinput" /></td>
<td><input type="checkbox" disabled="disabled" checked="checked" class="myinput" /></td>
</tr>
<tr>
<td>Large:</td>
<td><input type="checkbox" class="myinput large" /></td>
<td><input type="checkbox" checked="checked" class="myinput large" /></td>
<td><input type="checkbox" disabled="disabled" class="myinput large" /></td>
<td><input type="checkbox" disabled="disabled" checked="checked" class="myinput large" /></td>
</tr>
<tr>
<td>Custom icon:</td>
<td><input type="checkbox" class="myinput large custom" /></td>
<td><input type="checkbox" checked="checked" class="myinput large custom" /></td>
<td><input type="checkbox" disabled="disabled" class="myinput large custom" /></td>
<td><input type="checkbox" disabled="disabled" checked="checked" class="myinput large custom" /></td>
</tr>
</table>
$(function() {
var f = function() {
$(this).next().text($(this).is(':checked') ? ':checked' : ':not(:checked)');
};
$('input').change(f).trigger('change');
});
body {
font-family: arial;
}
.flipswitch {
position: relative;
background: white;
width: 120px;
height: 40px;
-webkit-appearance: initial;
border-radius: 3px;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
outline: none;
font-size: 14px;
font-family: Trebuchet, Arial, sans-serif;
font-weight: bold;
cursor: pointer;
border: 1px solid #ddd;
}
.flipswitch:after {
position: absolute;
top: 5%;
display: block;
line-height: 32px;
width: 45%;
height: 90%;
background: #fff;
box-sizing: border-box;
text-align: center;
transition: all 0.3s ease-in 0s;
color: black;
border: #888 1px solid;
border-radius: 3px;
}
.flipswitch:after {
left: 2%;
content: "OFF";
}
.flipswitch:checked:after {
left: 53%;
content: "ON";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<h2>Webkit friendly mobile-style checkbox/flipswitch</h2>
<input type="checkbox" class="flipswitch" />
<span></span>
<br>
<input type="checkbox" checked="checked" class="flipswitch" />
<span></span>
시작하기 전 (2015년 1월 기준)
원래 문답은 5세까지입니다.따라서 이것은 약간의 업데이트입니다.
우선 스타일링 체크박스에 관해서는 몇 가지 방법이 있습니다.기본 원칙은 다음과 같습니다.
브라우저에 의해 스타일링되는 기본 체크박스컨트롤을 숨겨야 합니다.CSS를 사용하여 의미 있는 방법으로 덮어쓸 수 없습니다.
컨트롤을 숨기더라도 선택한 상태를 감지하고 전환할 수 있어야 합니다.
체크 박스의 체크 박스는, 새로운 요소의 스타일링에 반영할 필요가 있습니다.
해결책(원칙)
위의 내용은 여러 가지 방법으로 실행할 수 있습니다.또한 CSS3 의사 요소를 사용하는 것이 올바른 방법이라는 이야기도 자주 듣게 됩니다.실제로 옳고 그른 방법은 없습니다.사용하는 상황에 가장 적합한 접근법에 따라 달라집니다.그렇긴 하지만, 제가 선호하는 것이 있습니다.
는 크크 a a a a a a a a a a a a a .
label의 임의의 할 수 .즉, 숨긴 경우에도 라벨 내의 아무 곳이나 클릭하여 체크 상태를 전환할 수 있습니다.확인란을 숨깁니다.
체크박스 뒤에 새 요소를 추가합니다.이것에 따라 스타일링을 합니다.체크박스 뒤에 표시되어야 합니다.그러면 CSS를 사용하여 선택할 수 있습니다.또한 이 체크박스에 따라서는
:checked는 'state를 선택할 수 . CSS 'backwards'를 선택합니다.
솔루션(코드)
label input {
visibility: hidden;/* <-- Hide the default checkbox. The rest is to hide and allow tabbing, which display:none prevents */
display: block;
height: 0;
width: 0;
position: absolute;
overflow: hidden;
}
label span {/* <-- Style the artificial checkbox */
height: 10px;
width: 10px;
border: 1px solid grey;
display: inline-block;
}
[type=checkbox]:checked + span {/* <-- Style its checked state */
background: black;
}
<label>
<input type='checkbox'>
<span></span>
Checkbox label text
</label>
구체화(아이콘 사용)
"하지만 이봐!"네가 소리치는 거 들었어.박스에 체크 표시를 하거나 십자가 표시를 하고 싶으면요?그리고 나는 배경 이미지를 사용하고 싶지 않아!
CSS3는 CSS3로 되어 있습니다.은 「」를 하고 있습니다.content어느 하나의 상태를 나타내는 Unicode 아이콘을 삽입할 수 있는 속성입니다.또는 서드파티 폰트 아이콘 소스(font awesome 등)를 사용할 수도 있습니다(단, 관련 설정도 필요합니다).font-family "To" 로),FontAwesome)
label input {
display: none; /* Hide the default checkbox */
}
/* Style the artificial checkbox */
label span {
height: 10px;
width: 10px;
border: 1px solid grey;
display: inline-block;
position: relative;
}
/* Style its checked state...with a ticked icon */
[type=checkbox]:checked + span:before {
content: '\2714';
position: absolute;
top: -5px;
left: 0;
}
<label>
<input type='checkbox'>
<span></span>
Checkbox label text
</label>
CSS만을 사용하여 이를 수행하는 방법이 있습니다.는 (남용)을수 있다.label대신 해당 요소를 스타일링합니다.주 : Internet Explorer 8 。
.myCheckbox input {
position: relative;
z-index: -9999;
}
.myCheckbox span {
width: 20px;
height: 20px;
display: block;
background: url("link_to_image");
}
.myCheckbox input:checked + span {
background: url("link_to_another_image");
}
<label for="test">Label for my styled "checkbox"</label>
<label class="myCheckbox">
<input type="checkbox" name="test" />
<span></span>
</label>
접근 가능한 최신 솔루션 - 사용accent-color
새 속성을 사용하여 접근성을 보장하기 위해 3:1의 적절한 콘트라스트비를 충족하는지 확인하십시오.이 방법도 유효합니다.radio버튼을 클릭합니다.
.red-input {
accent-color: #9d3039;
height: 20px; /* not needed */
width: 20px; /* not needed */
}
<input class="red-input" type="checkbox" />
<!-- Radio button example -->
<input class="red-input" type="radio" />
오래된 답변입니다. 위의 내용보다 더 많은 커스터마이즈가 필요한 경우에만 이 방법을 권장합니다.
나는 스크롤과 스크롤을 해왔고 이 답변들 중 많은 것들이 단순히 접근성을 문 밖으로 던져버리고 WCAG를 두 가지 이상의 방법으로 위반하고 있다.대부분의 경우 커스텀 체크박스를 사용할 때 커스텀 라디오 버튼도 원하기 때문에 라디오 버튼을 추가했습니다.
만지작거림:
- 체크박스 - 순수 CSS - 서드파티 라이브러리가 없음
- 서드파티 라이브러리가 없는 순수 CSS 라디오 버튼
- FontAwesome을 사용하지만 Gliphicon 등과 쉽게 스왑할 수 있는 체크박스*
파티에 늦었지만 2019년, 2020년, 2021년에도 여전히 어렵기 때문에 접근하기 쉽고 쉽게 접근할 수 있는 3가지 솔루션을 추가했습니다.
이것들은 모두 JavaScript 프리, 액세스 가능, 외부 라이브러리 프리* 입니다.
이것들 중 하나로 플러그 앤 플레이를 하고 싶은 경우는, 스타일 시트를 핀들에서 카피하고, 필요에 따라서 CSS 로 컬러 코드를 편집해, 이동해 주세요.체크박스를 켜려면 커스텀 svg 체크마크아이콘을 추가할 수 있습니다.CSSY가 아닌 사람들을 위해 많은 코멘트를 추가했습니다.
긴 텍스트 또는 작은 컨테이너가 있고 확인란 또는 라디오 버튼 입력 아래에 텍스트 래핑이 있는 경우 다음과 같은 div로 변환하십시오.
자세한 설명:나는 WCAG를 위반하지 않고 JavaScript나 외부 라이브러리에 의존하지 않으며, 선택하기 위한 탭이나 스페이스바 같은 키보드 네비게이션을 중단하지 않고, 포커스 이벤트를 허용하는 솔루션, 체크박스와 체크박스를 모두 비활성화할 수 있는 솔루션이 필요했다.그리고 마지막으로 체크박스의 모양을 원하는 대로 커스터마이즈할 수 있는 솔루션background-colorborder-radius,svg배경 등
저는 @Jan Turo to의 답변을 조합하여 저만의 해결책을 생각해 냈는데, 꽤 효과가 있을 것 같습니다.라디오 버튼도 사용하기 위해 체크박스에서 같은 코드를 많이 사용하는 바이올린을 만들었습니다.
저는 아직 접근성을 배우고 있기 때문에, 뭔가 놓친 것이 있으면 코멘트를 남겨 주시면 수정하도록 하겠습니다.
체크박스의 코드 예를 다음에 나타냅니다.
input[type="checkbox"] {
position: absolute;
opacity: 0;
z-index: -1;
}
/* Text color for the label */
input[type="checkbox"]+span {
cursor: pointer;
font: 16px sans-serif;
color: black;
}
/* Checkbox un-checked style */
input[type="checkbox"]+span:before {
content: '';
border: 1px solid grey;
border-radius: 3px;
display: inline-block;
width: 16px;
height: 16px;
margin-right: 0.5em;
margin-top: 0.5em;
vertical-align: -2px;
}
/* Checked checkbox style (in this case the background is green #e7ffba, change this to change the color) */
input[type="checkbox"]:checked+span:before {
/* NOTE: Replace the url with a path to an SVG of a checkmark to get a checkmark icon */
background-image: url('https://cdnjs.cloudflare.com/ajax/libs/ionicons/4.5.6/collection/build/ionicons/svg/ios-checkmark.svg');
background-repeat: no-repeat;
background-position: center;
/* The size of the checkmark icon, you may/may not need this */
background-size: 25px;
border-radius: 2px;
background-color: #e7ffba;
color: white;
}
/* Adding a dotted border around the active tabbed-into checkbox */
input[type="checkbox"]:focus+span:before,
input[type="checkbox"]:not(:disabled)+span:hover:before {
/* Visible in the full-color space */
box-shadow: 0px 0px 0px 2px rgba(0, 150, 255, 1);
/* Visible in Windows high-contrast themes
box-shadow will be hidden in these modes and
transparency will not be hidden in high-contrast
thus box-shadow will not show but the outline will
providing accessibility */
outline-color: transparent; /*switch to transparent*/
outline-width: 2px;
outline-style: dotted;
}
/* Disabled checkbox styles */
input[type="checkbox"]:disabled+span {
cursor: default;
color: black;
opacity: 0.5;
}
/* Styles specific to this fiddle that you do not need */
body {
padding: 1em;
}
h1 {
font-size: 18px;
}
<h1>
NOTE: Replace the url for the background-image in CSS with a path to an SVG in your solution or CDN. This one was found from a quick google search for a checkmark icon cdn
</h1>
<p>You can easily change the background color, checkbox symbol, border-radius, etc.</p>
<label>
<input type="checkbox">
<span>Try using tab and space</span>
</label>
<br>
<label>
<input type="checkbox" checked disabled>
<span>Disabled Checked Checkbox</span>
</label>
<br>
<label>
<input type="checkbox" disabled>
<span>Disabled Checkbox</span>
</label>
<br>
<label>
<input type="checkbox">
<span>Normal Checkbox</span>
</label>
<br>
<label>
<input type="checkbox">
<span>Another Normal Checkbox</span>
</label>
는 항상 요소를 합니다.:before ★★★★★★★★★★★★★★★★★」:after마법처럼 잘 통합니다.
자세한 내용은 이 링크를 참조하십시오.
순서
- 규칙을 .
visibility:hidden★★★★★★★★★★★★★★★★★」opacity:0★★★★★★★★★★★★★★★★★」position:absolute;left:-9999pxsyslog. - 를 만듭니다.
:before를 지정하고 또는 없는 합니다.'\00a0'; - 박스가 「」에 있는 .
:checked, Unicode 전달content: "\2713" :focusstyle을 합니다.- 다 했어요.
내가 한 방법은 이렇다.
.box {
background: #666666;
color: #ffffff;
width: 250px;
padding: 10px;
margin: 1em auto;
}
p {
margin: 1.5em 0;
padding: 0;
}
input[type="checkbox"] {
visibility: hidden;
}
label {
cursor: pointer;
}
input[type="checkbox"] + label:before {
border: 1px solid #333;
content: "\00a0";
display: inline-block;
font: 16px/1em sans-serif;
height: 16px;
margin: 0 .25em 0 0;
padding: 0;
vertical-align: top;
width: 16px;
}
input[type="checkbox"]:checked + label:before {
background: #fff;
color: #333;
content: "\2713";
text-align: center;
}
input[type="checkbox"]:checked + label:after {
font-weight: bold;
}
input[type="checkbox"]:focus + label::before {
outline: rgb(59, 153, 252) auto 5px;
}
<div class="content">
<div class="box">
<p>
<input type="checkbox" id="c1" name="cb">
<label for="c1">Option 01</label>
</p>
<p>
<input type="checkbox" id="c2" name="cb">
<label for="c2">Option 02</label>
</p>
<p>
<input type="checkbox" id="c3" name="cb">
<label for="c3">Option 03</label>
</p>
</div>
</div>
★★★★★★★★★★★★★로 :before ★★★★★★★★★★★★★★★★★」:after
body{
font-family: sans-serif;
}
.container {
margin-top: 50px;
margin-left: 20px;
margin-right: 20px;
}
.checkbox {
width: 100%;
margin: 15px auto;
position: relative;
display: block;
}
.checkbox input[type="checkbox"] {
width: auto;
opacity: 0.00000001;
position: absolute;
left: 0;
margin-left: -20px;
}
.checkbox label {
position: relative;
}
.checkbox label:before {
content: '';
position: absolute;
left: 0;
top: 0;
margin: 4px;
width: 22px;
height: 22px;
transition: transform 0.28s ease;
border-radius: 3px;
border: 2px solid #7bbe72;
}
.checkbox label:after {
content: '';
display: block;
width: 10px;
height: 5px;
border-bottom: 2px solid #7bbe72;
border-left: 2px solid #7bbe72;
-webkit-transform: rotate(-45deg) scale(0);
transform: rotate(-45deg) scale(0);
transition: transform ease 0.25s;
will-change: transform;
position: absolute;
top: 12px;
left: 10px;
}
.checkbox input[type="checkbox"]:checked ~ label::before {
color: #7bbe72;
}
.checkbox input[type="checkbox"]:checked ~ label::after {
-webkit-transform: rotate(-45deg) scale(1);
transform: rotate(-45deg) scale(1);
}
.checkbox label {
min-height: 34px;
display: block;
padding-left: 40px;
margin-bottom: 0;
font-weight: normal;
cursor: pointer;
vertical-align: sub;
}
.checkbox label span {
position: absolute;
top: 50%;
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
}
.checkbox input[type="checkbox"]:focus + label::before {
outline: 0;
}
<div class="container">
<div class="checkbox">
<input type="checkbox" id="checkbox" name="" value="">
<label for="checkbox"><span>Checkbox</span></label>
</div>
<div class="checkbox">
<input type="checkbox" id="checkbox2" name="" value="">
<label for="checkbox2"><span>Checkbox</span></label>
</div>
</div>
SW4의 답변을 따르겠습니다.더 이상 아닙니다.Volomike의 답변은 여기 있는 모든 답변보다 훨씬 우수합니다(답변 코멘트 개선 제안).대체 접근법에 대해 궁금한 경우 이 답변을 계속 읽어 보십시오. 이 답변은 다음과 같습니다.
먼저 체크박스를 끄고 커스텀스팬으로 커버합니다.다음 HTML을 제안합니다.
<label>
<input type="checkbox">
<span>send newsletter</span>
</label>
줄 바꿈 라벨을 깔끔하게 사용하면 "for-id" 속성 링크 없이 텍스트를 클릭할 수 있습니다.하지만,
.visibility: hidden ★★★★★★★★★★★★★★★★★」display: none
클릭이나 탭으로 동작하지만 체크박스를 사용하는 것은 좋지 않습니다.포커스를 이동하거나 활성화하거나 숨기거나 하면 포커스가 비활성화되는 사람도 있습니다.양식이 길면 손목을 아낄 수 있다.tabindex ★★★★★★★★★★★★★★★★★」accesskey체크박스의 호버에 .시스템 체크박스의 동작을 보면, 호버에 적당한 그림자가 있습니다.이 동작 뒤에 적절한 스타일의 체크박스가 표시됩니다.
Cobberboy의 답변은 글꼴이 확장 가능한 벡터이기 때문에 보통 비트맵보다 나은 Font Awesome을 추천한다.위의 HTML을 사용하여 다음 CSS 규칙을 사용할 것을 권장합니다.
확인란 숨기기
input[type="checkbox"] { position: absolute; opacity: 0; z-index: -1; }는 부정적으로만 .
z-index이 예에서는 체크박스를 완전히 커버할 수 있을 만큼 큰 체크박스를 사용하고 있기 때문입니다.하지 않습니다left: -999px모든 레이아웃에서 재사용할 수 있는 것은 아니기 때문입니다.Bushan Wagh의 답변은 이를 숨기고 브라우저가 tabindex를 사용하도록 설득할 수 있는 확실한 방법을 제공하므로 좋은 대안이 될 수 있다.어쨌든, 둘 다 그냥 해킹이야.오늘의 올바른 방법은appearance: noneJoost의 답변을 참조하십시오.input[type="checkbox"] { appearance: none; -webkit-appearance: none; -moz-appearance: none; }스타일 확인란 라벨
input[type="checkbox"] + span { font: 16pt sans-serif; color: #000; }확인란 스킨 추가
input[type="checkbox"] + span:before { font: 16pt FontAwesome; content: '\00f096'; display: inline-block; width: 16pt; padding: 2px 0 0 3px; margin-right: 0.5em; }
\00f096의 Font Awesome입니다.square-o패딩은 포커스에 도트 아웃라인을 균등하게 표시하도록 조정됩니다(아래 참조).
Add 체크박스가 켜져 있다.
input[type="checkbox"]:checked + span:before { content: '\00f046'; }
\00f046의 Font Awesome입니다.check-square-o, 너비가 square-o그래서 위 너비 스타일에 대한 이유입니다.
포커스 아웃라인 추가
input[type="checkbox"]:focus + span:before { outline: 1px dotted #aaa; }Safari는 이 기능을 제공하지 않습니다(@Jason Sankey의 코멘트 참조). Safari 전용 CSS에 대해서는 다음 답변을 참조하십시오.
비활성화 시 회색 설정 확인란
input[type="checkbox"]:disabled + span { color: #999; }사용하지 않도록 설정 확인란
input[type="checkbox"]:not(:disabled) + span:hover:before { text-shadow: 0 1px 2px #77F; }
JS Fielen에서 테스트합니다.
마우스를 체크박스 위로 가져가서+Tab 를 사용하여 이동하고 전환합니다.
CSS에서는, 「CSS」라고 하는 것은 않습니다.:before ★★★★★★★★★★★★★★★★★」:after환은없없 없없없다다기본 어피아란스를 끄고 다음 예시와 같이 인라인 배경 이미지로 스타일링할 수 있습니다.Chrome, Firefox, Safari 및( ( ( ( ( (( ( Chromium 엣지 )에서 작동합니다.
INPUT[type=checkbox]:focus
{
outline: 1px solid rgba(0, 0, 0, 0.2);
}
INPUT[type=checkbox]
{
background-color: #DDD;
border-radius: 2px;
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
width: 17px;
height: 17px;
cursor: pointer;
position: relative;
top: 5px;
}
INPUT[type=checkbox]:checked
{
background-color: #409fd6;
background: #409fd6 url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==") 3px 3px no-repeat;
}
<form>
<label><input type="checkbox"> I Agree To Terms & Conditions</label>
</form>
CSS Basic User Interface Module Level 4 c 、라고 하는 새로운 솔루션을 통해 (최종적으로) 이 지원이 추가되었습니다.accent-color다른 답변과는 달리 실제로는 매우 간단합니다.
input {
accent-color: rebeccapurple;
}
<input type="checkbox" />
있는 값,코드 을 'CSS'의 만 하면 accent-color용됩니니다다
이 기능은 현재 Chrome(v93+), Edge(v93+), Firefox(v92+), Opera(v79+) 및 Safari(v15.4+)에서 작동합니다.
주의:Safari는 수 는 현재 , Chrome ™ Opera('Safari')를 통한 rgba() 값) 중 )rgba()알파 채널은 브라우저에 의해 무시됩니다.)자세한 내용은 MDN 브라우저 지원을 참조하십시오.
구현이 간단하고 맞춤이 용이한 솔루션
많은 검색과 테스트를 거쳐 구현이 간단하고 커스터마이즈도 용이한 이 솔루션을 얻었습니다.이 솔루션에서는:
- 외부 라이브러리와 파일은 필요 없습니다.
- 페이지에 HTML을 추가할 필요가 없습니다.
- 확인란 이름 및 ID를 변경할 필요가 없습니다.
페이지 맨 위에 흐름 CSS를 놓으면 모든 체크박스의 스타일이 다음과 같이 바뀝니다.
input[type=checkbox] {
transform: scale(1.5);
}
input[type=checkbox] {
width: 30px;
height: 30px;
margin-right: 8px;
cursor: pointer;
font-size: 17px;
visibility: hidden;
}
input[type=checkbox]:after,
input[type=checkbox]::after {
content: " ";
background-color: #fff;
display: inline-block;
margin-left: 10px;
padding-bottom: 5px;
color: #00BFF0;
width: 22px;
height: 25px;
visibility: visible;
border: 1px solid #00BFF0;
padding-left: 3px;
border-radius: 5px;
}
input[type=checkbox]:checked:after,
input[type=checkbox]:checked::after {
content: "\2714";
padding: -5px;
font-weight: bold;
}
<input type="checkbox" id="checkbox1" />
<label for="checkbox1">Checkbox</label>
는 조금 할 수 .label요소의 예를 다음에 나타냅니다.
.checkbox > input[type=checkbox] {
visibility: hidden;
}
.checkbox {
position: relative;
display: block;
width: 80px;
height: 26px;
margin: 0 auto;
background: #FFF;
border: 1px solid #2E2E2E;
border-radius: 2px;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
}
.checkbox:after {
position: absolute;
display: inline;
right: 10px;
content: 'no';
color: #E53935;
font: 12px/26px Arial, sans-serif;
font-weight: bold;
text-transform: capitalize;
z-index: 0;
}
.checkbox:before {
position: absolute;
display: inline;
left: 10px;
content: 'yes';
color: #43A047;
font: 12px/26px Arial, sans-serif;
font-weight: bold;
text-transform: capitalize;
z-index: 0;
}
.checkbox label {
position: absolute;
display: block;
top: 3px;
left: 3px;
width: 34px;
height: 20px;
background: #2E2E2E;
cursor: pointer;
transition: all 0.5s linear;
-webkit-transition: all 0.5s linear;
-moz-transition: all 0.5s linear;
border-radius: 2px;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
z-index: 1;
}
.checkbox input[type=checkbox]:checked + label {
left: 43px;
}
<div class="checkbox">
<input id="checkbox1" type="checkbox" value="1" />
<label for="checkbox1"></label>
</div>
그리고 위 코드에 대한 FILED도.일부 CSS는 이전 버전의 브라우저에서 작동하지 않지만, 분명 멋진 JavaScript 예가 있을 것입니다!
추가 마크업을 하지 않아도 됩니다.은, CSS 의 을 개입시켜 를 한 모든 에서 동작합니다.appearance:
input[type="checkbox"] {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
/* Styling checkbox */
width: 16px;
height: 16px;
background-color: red;
}
input[type="checkbox"]:checked {
background-color: green;
}
<input type="checkbox" />
최근에 나는 그 문제에 대한 꽤 흥미로운 해결책을 찾았다.
하면 .appearance: none;체크박스의 기본 스타일을 해제하고 여기에 설명된 대로 체크박스에 자신의 스타일을 씁니다(예 4).
input[type=checkbox] {
width: 23px;
height: 23px;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
margin-right: 10px;
background-color: #878787;
outline: 0;
border: 0;
display: inline-block;
-webkit-box-shadow: none !important;
-moz-box-shadow: none !important;
box-shadow: none !important;
}
input[type=checkbox]:focus {
outline: none;
border: none !important;
-webkit-box-shadow: none !important;
-moz-box-shadow: none !important;
box-shadow: none !important;
}
input[type=checkbox]:checked {
background-color: green;
text-align: center;
line-height: 15px;
}
<input type="checkbox">
지원은 '''에 좋지 않습니다.appearance from. 동작했습니다.오페라 크롬하지만 더 나은 지원이 제공되거나 Chrome/Opera만 사용하고자 할 때는 이 방법이 단순함을 유지하는 방법입니다.
아이콘 폰트(Font Awesome 등)는 CSS로 쉽게 색상을 변경할 수 있고 고화소 밀도 디바이스에서도 확장이 가능하기 때문에 사용하는 것을 선호합니다.여기 또 다른 순수 CSS 변종이 있습니다.상기와 유사한 기술을 사용하고 있습니다.
(아래는 정적 이미지이므로 결과를 시각화할 수 있습니다.인터랙티브 버전에 대해서는, JSFiddle 를 참조해 주세요).

해결책과 로, 이 은 as른른 as as as as as as as as as as as as as as as as as 를 사용합니다.label인접하다span이치노
span.bigcheck-target {
font-family: FontAwesome; /* Use an icon font for the checkbox */
}
input[type='checkbox'].bigcheck {
position: relative;
left: -999em; /* Hide the real checkbox */
}
input[type='checkbox'].bigcheck + span.bigcheck-target:after {
content: "\f096"; /* In fontawesome, is an open square (fa-square-o) */
}
input[type='checkbox'].bigcheck:checked + span.bigcheck-target:after {
content: "\f046"; /* fontawesome checked box (fa-check-square-o) */
}
/* ==== Optional - colors and padding to make it look nice === */
body {
background-color: #2C3E50;
color: #D35400;
font-family: sans-serif;
font-weight: 500;
font-size: 4em; /* Set this to whatever size you want */
}
span.bigcheck {
display: block;
padding: 0.5em;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
<span class="bigcheck">
<label class="bigcheck">
Cheese
<input type="checkbox" class="bigcheck" name="cheese" value="yes" />
<span class="bigcheck-target"></span>
</label>
</span>
여기 JSFiddle이 있습니다.
나의 솔루션
input[type="checkbox"] {
cursor: pointer;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
outline: 0;
background: lightgray;
height: 16px;
width: 16px;
border: 1px solid white;
}
input[type="checkbox"]:checked {
background: #2aa1c0;
}
input[type="checkbox"]:hover {
filter: brightness(90%);
}
input[type="checkbox"]:disabled {
background: #e6e6e6;
opacity: 0.6;
pointer-events: none;
}
input[type="checkbox"]:after {
content: '';
position: relative;
left: 40%;
top: 20%;
width: 15%;
height: 40%;
border: solid #fff;
border-width: 0 2px 2px 0;
transform: rotate(45deg);
display: none;
}
input[type="checkbox"]:checked:after {
display: block;
}
input[type="checkbox"]:disabled:after {
border-color: #7b7b7b;
}
<input type="checkbox"><br>
<input type="checkbox" checked><br>
<input type="checkbox" disabled><br>
<input type="checkbox" disabled checked><br>
사용하시면 .appearance: none기본 스타일링이 없고 모든 스타일이 올바르게 적용되도록 최신 브라우저의 경우:
input[type=checkbox] {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
display: inline-block;
width: 2em;
height: 2em;
border: 1px solid gray;
outline: none;
vertical-align: middle;
}
input[type=checkbox]:checked {
background-color: blue;
}
다음은 jQuery 또는 JavaScript 코드가 없는 단순한 CSS 솔루션입니다.
나는 FontAwseome 아이콘을 사용하고 있지만 당신은 어떤 이미지라도 사용할 수 있다.
input[type=checkbox] {
display: inline-block;
font-family: FontAwesome;
font-style: normal;
font-weight: normal;
line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
visibility: hidden;
font-size: 14px;
}
input[type=checkbox]:before {
content: @fa-var-square-o;
visibility: visible;
/*font-size: 12px;*/
}
input[type=checkbox]:checked:before {
content: @fa-var-check-square-o;
}
제 구글링으로는 체크박스를 가장 쉽게 스타일링 할 수 있습니다. 더하면 돼요.:after ★★★★★★★★★★★★★★★★★」:checked:afterCSS.
body{
background: #DDD;
}
span{
margin-left: 30px;
}
input[type=checkbox] {
cursor: pointer;
font-size: 17px;
visibility: hidden;
position: absolute;
top: 0;
left: 0;
transform: scale(1.5);
}
input[type=checkbox]:after {
content: " ";
background-color: #fff;
display: inline-block;
color: #00BFF0;
width: 14px;
height: 19px;
visibility: visible;
border: 1px solid #FFF;
padding: 0 3px;
margin: 2px 0;
border-radius: 8px;
box-shadow: 0 0 15px 0 rgba(0,0,0,0.08), 0 0 2px 0 rgba(0,0,0,0.16);
}
input[type=checkbox]:checked:after {
content: "\2714";
display: unset;
font-weight: bold;
}
<input type="checkbox"> <span>Select Text</span>
플레인 CSS를 사용하여 체크박스 스타일을 변경합니다.이를 위해 JavaScript 또는 HTML 조작이 필요하지 않습니다.
.form input[type="checkbox"]:before {
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
content: "\f096";
opacity: 1 !important;
margin-top: -25px;
appearance: none;
background: #fff;
}
.form input[type="checkbox"]:checked:before {
content: "\f046";
}
.form input[type="checkbox"] {
font-size: 22px;
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<form class="form">
<input type="checkbox" />
</form>
이런! 이 모든 회피책들을 통해 HTML 체크박스를 스타일링하고 싶다면 좀 형편없다는 결론을 내리게 되었습니다.
경고로서 이것은 CSS의 실장이 아닙니다.다른 사람이 유용하다고 생각할 경우를 대비해서 제가 생각해 낸 해결 방법을 공유하려고요.
HTML5를 했습니다.canvas★★★★★★ 。
이 방법의 장점은 외부 이미지를 사용할 필요가 없고 대역폭을 절약할 수 있다는 것입니다.
단점은 브라우저가 어떤 이유로 올바르게 렌더링할 수 없는 경우 폴백이 없다는 것입니다.하지만 이것이 2017년에도 이슈로 남아있을지는 논란의 여지가 있다.
갱신하다
나는 오래된 코드가 꽤 보기 흉하다는 것을 알았기 때문에 다시 쓰기로 했다.
Object.prototype.create = function(args){
var retobj = Object.create(this);
retobj.constructor(args || null);
return retobj;
}
var Checkbox = Object.seal({
width: 0,
height: 0,
state: 0,
document: null,
parent: null,
canvas: null,
ctx: null,
/*
* args:
* name default desc.
*
* width 15 width
* height 15 height
* document window.document explicit document reference
* target this.document.body target element to insert checkbox into
*/
constructor: function(args){
if(args === null)
args = {};
this.width = args.width || 15;
this.height = args.height || 15;
this.document = args.document || window.document;
this.parent = args.target || this.document.body;
this.canvas = this.document.createElement("canvas");
this.ctx = this.canvas.getContext('2d');
this.canvas.width = this.width;
this.canvas.height = this.height;
this.canvas.addEventListener("click", this.ev_click(this), false);
this.parent.appendChild(this.canvas);
this.draw();
},
ev_click: function(self){
return function(unused){
self.state = !self.state;
self.draw();
}
},
draw_rect: function(color, offset){
this.ctx.fillStyle = color;
this.ctx.fillRect(offset, offset,
this.width - offset * 2, this.height - offset * 2);
},
draw: function(){
this.draw_rect("#CCCCCC", 0);
this.draw_rect("#FFFFFF", 1);
if(this.is_checked())
this.draw_rect("#000000", 2);
},
is_checked: function(){
return !!this.state;
}
});
여기 작업용 데모가 있습니다.
새 버전은 프로토타입과 차등 상속을 사용하여 확인란을 만드는 효율적인 시스템을 만듭니다.체크박스를 작성하려면:
var my_checkbox = Checkbox.create();
그러면 DOM에 체크박스가 즉시 추가되고 이벤트가 연결됩니다.체크박스가 켜져 있는지 여부를 문의하려면:
my_checkbox.is_checked(); // True if checked, else false
루프를 제거했다는 점도 중요합니다.
업데이트 2
지난 번 업데이트에서 언급하지 않은 것은 캔버스를 사용하는 것이 단순히 원하는 대로 보이는 체크박스를 만드는 것보다 더 많은 장점이 있다는 것입니다.필요에 따라 다중 상태 확인란을 만들 수도 있습니다.
Object.prototype.create = function(args){
var retobj = Object.create(this);
retobj.constructor(args || null);
return retobj;
}
Object.prototype.extend = function(newobj){
var oldobj = Object.create(this);
for(prop in newobj)
oldobj[prop] = newobj[prop];
return Object.seal(oldobj);
}
var Checkbox = Object.seal({
width: 0,
height: 0,
state: 0,
document: null,
parent: null,
canvas: null,
ctx: null,
/*
* args:
* name default desc.
*
* width 15 width
* height 15 height
* document window.document explicit document reference
* target this.document.body target element to insert checkbox into
*/
constructor: function(args){
if(args === null)
args = {};
this.width = args.width || 15;
this.height = args.height || 15;
this.document = args.document || window.document;
this.parent = args.target || this.document.body;
this.canvas = this.document.createElement("canvas");
this.ctx = this.canvas.getContext('2d');
this.canvas.width = this.width;
this.canvas.height = this.height;
this.canvas.addEventListener("click", this.ev_click(this), false);
this.parent.appendChild(this.canvas);
this.draw();
},
ev_click: function(self){
return function(unused){
self.state = !self.state;
self.draw();
}
},
draw_rect: function(color, offsetx, offsety){
this.ctx.fillStyle = color;
this.ctx.fillRect(offsetx, offsety,
this.width - offsetx * 2, this.height - offsety * 2);
},
draw: function(){
this.draw_rect("#CCCCCC", 0, 0);
this.draw_rect("#FFFFFF", 1, 1);
this.draw_state();
},
draw_state: function(){
if(this.is_checked())
this.draw_rect("#000000", 2, 2);
},
is_checked: function(){
return this.state == 1;
}
});
var Checkbox3 = Checkbox.extend({
ev_click: function(self){
return function(unused){
self.state = (self.state + 1) % 3;
self.draw();
}
},
draw_state: function(){
if(this.is_checked())
this.draw_rect("#000000", 2, 2);
if(this.is_partial())
this.draw_rect("#000000", 2, (this.height - 2) / 2);
},
is_partial: function(){
return this.state == 2;
}
});
했습니다.Checkbox마지막 스니펫에서 사용되므로 보다 일반적이기 때문에 3개의 상태를 가진 체크박스를 사용하여 해당 스니펫을 "수정"할 수 있습니다.여기 데모가 있습니다.보시는 바와 같이 이미 내장된 체크박스보다 더 많은 기능을 갖추고 있습니다.
JavaScript와 CSS 중 하나를 선택할 때 고려해야 할 사항.
오래되고 제대로 설계되지 않은 코드
먼저 캔버스를 세팅
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
checked = 0; // The state of the checkbox
canvas.width = canvas.height = 15; // Set the width and height of the canvas
document.body.appendChild(canvas);
document.body.appendChild(document.createTextNode(' Togglable Option'));
다음으로 캔버스 자체를 갱신하는 방법을 생각해냅니다.
(function loop(){
// Draws a border
ctx.fillStyle = '#ccc';
ctx.fillRect(0,0,15,15);
ctx.fillStyle = '#fff';
ctx.fillRect(1, 1, 13, 13);
// Fills in canvas if checked
if(checked){
ctx.fillStyle = '#000';
ctx.fillRect(2, 2, 11, 11);
}
setTimeout(loop, 1000/10); // Refresh 10 times per second
})();
마지막은 인터랙티브하게 하는 거예요.다행히, 이것은 매우 간단합니다.
canvas.onclick = function(){
checked = !checked;
}
JavaScript의 이상한 이벤트 처리 모델 때문에 IE에서 문제가 발생할 수 있습니다.
나는 이것이 누군가에게 도움이 되기를 바란다. 그것은 확실히 나의 요구에 부합했다.
SCSS/SAS의 실장
보다 현대적인 접근법
SCSS(또는 쉽게 SAS로 변환)를 사용하는 사용자에게 다음 사항이 도움이 됩니다.실제로 체크박스 옆에 요소를 만듭니다.이것이 스타일링 하는 요소입니다.이 체크박스를 클릭하면 CSS는 (새로 체크된 스타일에) 자매 요소를 재시작합니다.코드는 다음과 같습니다.
label.checkbox {
input[type="checkbox"] {
visibility: hidden;
display: block;
height: 0;
width: 0;
position: absolute;
overflow: hidden;
&:checked + span {
background: $accent;
}
}
span {
cursor: pointer;
height: 15px;
width: 15px;
border: 1px solid $accent;
border-radius: 2px;
display: inline-block;
transition: all 0.2s $interpol;
}
}
<label class="checkbox">
<input type="checkbox" />
<span></span>
Label text
</label>
심플하고 가벼운 템플릿:
input[type=checkbox] {
cursor: pointer;
}
input[type=checkbox]:checked:before {
content: "\2713";
background: #fffed5;
text-shadow: 1px 1px 1px rgba(0, 0, 0, .2);
font-size: 20px;
text-align: center;
line-height: 8px;
display: inline-block;
width: 13px;
height: 15px;
color: #00904f;
border: 1px solid #cdcdcd;
border-radius: 4px;
margin: -3px -3px;
text-indent: 1px;
}
input[type=checkbox]:before {
content: "\202A";
background: #ffffff;
text-shadow: 1px 1px 1px rgba(0, 0, 0, .2);
font-size: 20px;
text-align: center;
line-height: 8px;
display: inline-block;
width: 13px;
height: 15px;
color: #00904f;
border: 1px solid #cdcdcd;
border-radius: 4px;
margin: -3px -3px;
text-indent: 1px;
}
<input type="checkbox" checked="checked">checked1<br>
<input type="checkbox">unchecked2<br>
<input type="checkbox" checked="checked" id="id1">
<label for="id1">checked2+label</label><br>
<label for="id2">unchecked2+label+rtl</label>
<input type="checkbox" id="id2">
<br>
https://jsfiddle.net/rvgccn5b/
을 하는 이라고 생각합니다.label ①을 ,checkbox보이지 않는
HTML
<input type="checkbox" id="first" />
<label for="first"> </label>
CSS
checkbox {
display: none;
}
checkbox + label {
/* Style for checkbox normal */
width: 16px;
height: 16px;
}
checkbox::checked + label,
label.checked {
/* Style for checkbox checked */
}
checkbox는 숨겨져 있어도 액세스 할 수 있으며, 그 값은 폼이 송신될 때 송신됩니다., ' 변경'이할 수 .label Explorer는 "Internet Explorer"를 하지 못할 같기 때문에 JavaScript를 합니다.::checked checkbox.
다음은 간단한 애니메이션과 간단한 스타일링이 포함된 최신 버전입니다.
.checkbox {
position: relative;
width: 20px;
height: 20px;
-webkit-appearance: none;
-moz-appearance: none;
-o-appearance: none;
appearance: none;
background: transparent;
border: 2px solid #7C7A7D;
border-radius: 5px;
margin: 0;
outline: none;
transition: 0.5s ease;
opacity: 0.8;
cursor: pointer;
}
.checkbox:checked {
border-color: #7C7A7D;
background-color: #7C7A7D;
}
.checkbox:checked:before {
position: absolute;
left: 2px;
top: -4px;
display: block;
content: '\2713';
text-align: center;
color: #FFF;
font-family: Arial;
font-size: 14px;
font-weight: 800;
}
.checkbox:hover {
opacity: 1.0;
transform: scale(1.05);
}
JavaScript 또는 jQuery는 필요하지 않습니다.
확인란 스타일을 단순하게 변경합니다.
input[type="checkbox"] {
display: none;
border: none !important;
box-shadow: none !important;
}
input[type="checkbox"] + label span {
background: url(http://imgh.us/uncheck.png);
width: 49px;
height: 49px;
display: inline-block;
vertical-align: middle;
}
input[type="checkbox"]:checked + label span {
background: url(http://imgh.us/check_2.png);
width: 49px;
height: 49px;
vertical-align: middle;
}
<input type="checkbox" id="option" />
<label for="option"> <span></span> Click me </label>
CSS를 사용한 커스텀 체크박스(WebKit 브라우저 솔루션만 Chrome, Safari, 모바일브라우저)
<input type="checkbox" id="cardAccptance" name="cardAccptance" value="Yes">
<label for="cardAccptance" class="bold"> Save Card for Future Use</label>
CSS:
/* The checkbox-cu */
.checkbox-cu {
display: block;
position: relative;
padding-left: 35px;
margin-bottom: 0;
cursor: pointer;
font-size: 16px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* Hide the browser's default checkbox-cu */
.checkbox-cu input {
position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;
}
/* Create a custom checkbox-cu */
.checkmark {
position: absolute;
top: 4px;
left: 0;
height: 20px;
width: 20px;
background-color: #eee;
border: 1px solid #999;
border-radius: 0;
box-shadow: none;
}
/* On mouse-over, add a grey background color */
.checkbox-cu:hover input~.checkmark {
background-color: #ccc;
}
/* When the checkbox-cu is checked, add a blue background */
.checkbox-cu input:checked~.checkmark {
background-color: transparent;
}
/* Create the checkmark/indicator (hidden when not checked) */
.checkmark:after {
content: "";
position: absolute;
display: none;
}
/* Show the checkmark when checked */
.checkbox-cu input:checked~.checkmark:after {
display: block;
}
/* Style the checkmark/indicator */
.checkbox-cu .checkmark::after {
left: 7px;
top: 3px;
width: 6px;
height: 9px;
border: solid #28a745;
border-width: 0 2px 2px 0;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
z-index: 100;
}
사용자 정의 스타일시트와 함께 재료화를 사용하면 다음과 같은 작업을 수행할 수 있습니다.
CSS 코드
.custom_checkbox[type="checkbox"]:checked + span:not(.lever)::before {
border: 2px solid transparent;
border-bottom: 2px solid #ffd600;
border-right: 2px solid #ffd600;
background: transparent;
}
HTML 코드
<label>
<input type="checkbox" class="custom_checkbox" />
<span>Text</span>
</label>
데모
체크박스의 스타일(색상)을 변경하는 데 도움이 되었습니다.
input[type=checkbox] {
accent-color: red;
}
라디오 버튼에도 같은 것을 사용할 수 있습니다.
이것이 가장 간단한 방법이며 이 스타일을 지정할 확인란을 선택할 수 있습니다.
CSS:
.check-box input {
display: none;
}
.check-box span:before {
content: ' ';
width: 20px;
height: 20px;
display: inline-block;
background: url("unchecked.png");
}
.check-box input:checked + span:before {
background: url("checked.png");
}
HTML:
<label class="check-box">
<input type="checkbox">
<span>Check box Text</span>
</label>
이것은 CSS/HTML 전용 버전이며 jQuery 또는 JavaScript는 전혀 필요하지 않습니다.HTML은 심플하고 깔끔하며 매우 심플하고 짧은 CSS입니다.
여기 JSFiddle이 있습니다.
HTML은 다음과 같습니다.
<div id="myContainer">
<input type="checkbox" name="myCheckbox" id="myCheckbox_01_item" value="red" />
<label for="myCheckbox_01_item" class="box"></label>
<label for="myCheckbox_01_item" class="text">I accept the Terms of Use.</label>
</div>
여기 CSS가 있습니다.
#myContainer {
outline: black dashed 1px;
width: 200px;
}
#myContainer input[type="checkbox"][name="myCheckbox"] {
display: none;
}
#myContainer input[type="checkbox"][name="myCheckbox"]:not(:checked) + label.box {
display: inline-block;
width: 25px;
height: 25px;
border: black solid 1px;
background: #FFF ;
margin: 5px 5px;
}
#myContainer input[type="checkbox"][name="myCheckbox"]:checked + label.box {
display: inline-block;
width: 25px;
height: 25px;
border: black solid 1px;
background: #F00;
margin: 5px 5px;
}
#myContainer input[type="checkbox"][name="myCheckbox"] + label + label.text {
font: normal 12px arial;
display: inline-block;
line-height: 27px;
vertical-align: top;
margin: 5px 0px;
}
개별 라디오 또는 체크박스, 체크박스 그룹 및 라디오 버튼 그룹도 사용할 수 있도록 조정할 수 있습니다.
이 html/css를 사용하면 라벨을 클릭하는 것도 캡처할 수 있기 때문에 라벨을 클릭하는 것만으로 체크박스가 켜지고 꺼집니다.
이 체크박스/라디오 버튼은 어떤 형태에서도 문제없이 사용할 수 있습니다.PHP, ASP를 사용하여 테스트 완료.NET(.aspx), Java Server Faces 및 Cold Fusion도 사용할 수 있습니다.
언급URL : https://stackoverflow.com/questions/4148499/how-to-style-a-checkbox-using-css
'codememo' 카테고리의 다른 글
| 스크롤 막대를 숨길 수 있지만 스크롤할 수 있음 (0) | 2023.04.08 |
|---|---|
| Powershell ISE에서 스크립트에 필요한 파라미터를 전달하려면 어떻게 해야 합니까? (0) | 2023.04.08 |
| PowerShell에서 "백업" 컨텍스트를 사용하여 섀도 복사본 생성 (0) | 2023.04.08 |
| PowerShell WMI 개체의 모든 속성을 나열하는 방법 (0) | 2023.04.08 |
| PowerShell에서 SQL Server 쿼리를 실행하려면 어떻게 해야 합니까? (0) | 2023.04.08 |
