0

I noticed this website has a list of checkboxes, but when I look at the HTML I just see div's with CSS classes on them.

How do you create checkboxes and check them off just by using CSS?

What is the benefit of doing it via CSS?

3
  • 1
    Check it: stackoverflow.com/questions/40929876/… Commented Nov 30, 2017 at 3:17
  • I would use backrgound-images, that are twice as tall as your div, making background-position:bottom; or background-position:top; onclick. Commented Nov 30, 2017 at 3:18
  • While this might look cool it is a potential mistake if you want the blind to be able to navigate your site. A screen reader won't know it is a checkbox unless you add several attributes to your pseudo checkbox. Commented Nov 30, 2017 at 3:34

1 Answer 1

0

You certainly can. The advantage is that it gives you way more flexibility. For example, here's a basic React component that uses divs for the checkbox:

https://jsbin.com/xarewiweza/1/edit?html,js,output

const styles = {
  outer: {
    borderRadius: 5,
    border: '2px solid gray',
    width: 30,
    height: 30,
    cursor: 'pointer',
  },
  inner: checked => ({
    borderRadius: '50%',
    height: 28,
    width: 28,
    backgroundColor: checked ? 'red' : 'transparent',
    margin: 1,
    transition: 'background-color 0.2s ease',
  })
}

class Checkbox extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      checked: false,
    }
  }

  render() {
    console.log(this.state)
    return (
      <div 
        onClick={() => this.setState({ checked: !this.state.checked, })}
        style={styles.outer}>
        <div style={styles.inner(this.state.checked)} />
      </div>
    )
  }
}

ReactDOM.render(<Checkbox />, document.body)

If you wanted animated checkmarks, or other cool stuff, you'd have to go custom.

The disadvantage is that you don't get some of the default HTML functionality, though I'm not sure if there is anything useful with the checkbox specifically. For example, with the default select on iOS, it automatically uses the carousel selecter, which is a handy feature.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.