Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an SVG checkbox?

Tags:

html

css

svg

I want to make a simple checkbox using an svg.

It doesn't have to be animated nor anything. I just want it to change the fill color when checked. As simple as that.

Here's my code:

<!DOCTYPE html>
<html>
    <header>

        <link href="{{ asset('css/app.css') }}" rel="stylesheet">

        <style>
        svg input:checked  {
            fill:yellow;
        }

        .my-image:hover {
            background-color:green;
            fill:red;
        }

        .my-image input:checked {
            fill:red;
        }

        </style>
    </header>

    <body>

        <label>
            <input type="checkbox" name="" value="" checked/>
            <svg class = "my-image" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="xMidYMid" width="17"
            height="16" viewBox="0 0 17 16">
            <path d="M8.500,0.000 L11.301,5.028 L16.999,6.112 L13.033,10.302 L13.753,16.000 L8.500,13.561 L3.247,16.000 L3.967,10.302 L0.001,6.112 L5.699,5.028 L8.500,0.000"
            class="cls-1" />
            </svg>

        </label>

        <script src="{{ asset('js/app.js') }}" type="application/javascript"></script>
    </body>
</html>

This is driving me absolutely crazy. The svg even has a red background that I don't know where it comes from.

enter image description here

I watched a lot of tutorials, read a lot and tried a lot of examples. None of them worked.

I just need a simple checkbox using svgs. Can you please help me out?

Also, I'm new to CSS and HTML. I'm sure I'm missing something.

Thanks.

like image 506
Luís Henriques Avatar asked Sep 13 '25 22:09

Luís Henriques


1 Answers

.my-image input:checked won't work this way, cause the input isn't a child element of .my-image and even if, the fill: red wouldn't be used for your image.

You could do something like this to achieve what you are trying:

  input[type="checkbox"]:checked + .my-image {
        fill:red;
  }

I created a fiddle where you can check it out: https://jsfiddle.net/uvt5zqr9/

In this fiddle the background isn't red, i guess maybe you have something in your app.css which causes the red background.

like image 118
twain Avatar answered Sep 16 '25 15:09

twain