Skip to main content

Archive

Show more

Foundation CSS Switch

Foundation CSS Switch

The Switch component in Foundation CSS provides a user-friendly way to toggle between two states, typically representing an "on" and "off" state. Switches are commonly used for settings, preferences, or binary options. Here's how you can use the Switch component:


1. Basic Switch

To create a basic Switch, use the <input> element with the type attribute set to checkbox.

Example markup:

<input type="checkbox">

This will generate a default Switch with two states: "on" and "off".


2. Customizing Switch Labels

You can customize the labels associated with the Switch by using the <label> element. This allows you to provide descriptive labels for the "on" and "off" states.

Example markup:

<label>
    <input type="checkbox">
    On Label
</label>
<label>
    <input type="checkbox">
    Off Label
</label>

This will create a Switch with custom labels for the "on" and "off" states.


3. Styling the Switch

You can apply custom styles to the Switch using CSS. Foundation CSS provides classes for styling various aspects of the Switch, such as its appearance, size, and colors.

Example markup:

<input type="checkbox" id="customSwitch">
<label for="customSwitch" class="switch">Toggle Me</label>

Example CSS:

.switch {
    position: relative;
    display: inline-block;
    width: 60px;
    height: 34px;
}

.switch input {
    opacity: 0;
    width: 0;
    height: 0;
}

.slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    -webkit-transition: .4s;
    transition: .4s;
}

.slider:before {
    position: absolute;
    content: "";
    height: 26px;
    width: 26px;
    left: 4px;
    bottom: 4px;
    background-color: white;
    -webkit-transition: .4s;
    transition: .4s;
}

input:checked + .slider {
    background-color: #2196F3;
}

input:focus + .slider {
    box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
    -webkit-transform: translateX(26px);
    -ms-transform: translateX(26px);
    transform: translateX(26px);
}

This will create a styled Switch with a custom appearance and animation.


Conclusion

The Switch component in Foundation CSS offers an intuitive way to incorporate toggle functionality into your web applications. Whether you need a basic Switch or one with customized labels and styles, Foundation CSS provides the tools to create a Switch that fits your specific requirements.

Comments