Saturday, June 7, 2014

CSS3 trigger UI

How to make trigger UI using only CSS?

Once in a while there is a need to have some kind of trigger for checkbox functionality on the plage. Usually it is a regular <input type="checkbox"/> styled with background images like those: .
To use the styling based on background image you would need JS as INPUT itself does not have the ability to override the image on its container level during change event. There are some tricks how to do that properly as you do not want to use JS during page load to make the checkbox UI.
CSS3 gives you ability to implement the trigger UI design without any JS. The magic reside in ::before selector and background: linear-gradient. It is backward-compatible and shows regular checkbox where CSS3 is not available.

input[type='checkbox']{ display: block; width: 100%;margin:0; }
input[type='checkbox']::before
{ content: "OFF";
  display:block; padding: 0 1em 0 60%; color: white; font-weight: bold;
  text-align: "right";
  border: 1px solid black; border-radius: 3px;
  background: #73777b; /* Old browsers */
  background: linear-gradient(to right, #ffffff 0%,#ffffff 49%,#f1f1f1 50%,#73777b 51%,#73777b 100%);
  white-space: nowrap;
}
input[type='checkbox']:checked::before
{ content: "ON";
  padding: 0 60% 0 1em;
  background: #49aa50; /* Old browsers */
  background: linear-gradient(to right,  #49aa50 0%,#49aa50 49%,#f1f1f1 50%,#ffffff 51%,#ffffff 100%); /* W3C */
  white-space: nowrap;
}


Links: gradient-editor
Happy coding!

No comments:

Post a Comment