Tips for aligning an element vertically inside a relatively positioned parent element

Currently tackling a challenge with a toggle switch - the goal is to position the toggle knob perfectly vertical within the switch. Here's my attempted solution:

import style from "./Toggle.module.scss";

export default function Toggle() {
    return (
        <>
            <input type="checkbox" id="toggle" className={style.toggle} />
            <label htmlFor="toggle" className={style.label} />
        </>
    );
}

.toggle {
    height: 0;
    width: 0;
    opacity: 0;
}

.label {
    width:60px;
    height: 30px;
    border-radius:30px;
    display: block;
    background-color: #ebebeb;
    box-shadow: 1px 2px 5px 1px rgba(0,0,0,0.2) inset;
    left:10px;
    padding-left: 5px;
    position: relative;
    
    &::after {
        content: '';
        position: absolute;
        width: 23px;
        height: 23px;
        border-radius: 50px;
        background-color: green;
        top: 50%;
        transition: 0.3s;
        
    }
}

.toggle:checked ~ .label::after{
    transform: translateX(32px);

}

The objective is for the ::after property to be absolutely positioned relative to the label for perfect centering. However, it overflows as shown in the image:

https://i.sstatic.net/AJxsqWa8.png

The question is why does it work better without 'position: relative' than with 'relative'? Additionally, adding 'transform: translateY(-50%);' results in a diagonal movement when clicked.

Answer №1

Make sure to include the following style: "transform: translateY(-50%);" inside the &::after {}

Note: Remember to adjust the properties for react and convert them to SCSS.

.toggle {
    height: 0;
    width: 0;
    opacity: 0;
}

.label {
    width: 60px;
    height: 30px;
    border-radius: 30px;
    display: block;
    background-color: #ebebeb;
    box-shadow: 1px 2px 5px 1px rgba(0, 0, 0, 0.2) inset;
    left: 10px;
    padding-left: 5px;
    position: relative;
}

.label::after {
    content: '';
    position: absolute;
    width: 23px;
    height: 23px;
    border-radius: 50px;
    background-color: green;
    top: 50%;
    transition: 0.3s;
    transform: translateY(-50%);
}

.toggle:checked ~ .label::after {
    transform: translateX(32px) translateY(-50%);
}
<input type="checkbox" id="toggle" class="toggle"/>
<label for="toggle" class=label></label>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Find the initial element using the class name to retrieve the CSS properties

.class + p:first-child{ } The code above isn't functioning properly, unless it's an element instead of a class, like p:first-child. <div class="wrap"> <h3></h3> <div style="clear:both"></div> <p></p> & ...

Chrome displaying an extJs Button image

Could it be that Chrome is evolving into the new IE in terms of CSS issues? Here is the code I have for creating ExtJS buttons within an accordion: var button = Ext.create('Ext.Button', { text: '<img src="'+resp.sellers.externa ...

Storing the value of the current vertical scroll position in a variable using jQuery

I'm currently dealing with a challenge that involves using the value of (window).scrollTop() as a crucial variable in my project. What I aim to accomplish is to retrieve and utilize the specific scroll value at a particular moment within an if stateme ...

Retrieve a pre-signed URL from S3 and display a PDF or image in the browser

Looking to learn more about React, I am currently working on retrieving a pre-signed URL (s3) from an API and using it to display a PDF in the browser. Upon inspecting the network tab, I noticed two calls - one returning 308 and the other 200 with a respo ...

How can I move Bootstrap 5 navbar list items to the right side?

I'm struggling to position the signup and login links on the right side of the page. I've tried using mr-auto, ml-auto, and justify-content-end but none of them seem to be working. <nav class="navbar navbar-expand-lg navbar-light"&g ...

Help needed with React Native image loading issue - why won't the image load when passing a URI?

I am encountering an issue while trying to display an image on a screen in a react-native application. The image uri is being passed as props to the screen. Despite my efforts, the image is not loading and I am unsure of the reason. I have checked various ...

Is it possible to utilize CSS alone to change the color of a certain image to white against a black background?

I specialize in crafting dark theme versions of popular websites using CSS. One challenge I often face is dealing with images like the ones below: https://i.sstatic.net/ZLpPT.png https://i.sstatic.net/2NKRP.png Websites typically use background-image t ...

Issues with Implementing Scroll Directive in Angular JS

Apologies for asking what may seem like a silly question. I'm still new to using AngularJS and recently came across a neat little scroll directive on http://jsfiddle.net/88TzF/622/. However, when I tried implementing the code in the HTML snippet below ...

Tips on personalizing rows in an xlsx spreadsheet prior to exporting

When I receive an array of objects (dicts) as input, it looks something like the example below. const data = [ { id: 1, serviceId: 1, title: "A", model: "A", }, { id: 1, serviceId: 1, title: "T", model: "b", ...

Invalid prop type: The Grid component requires the justify prop to be used on a container

I encountered an issue while working with Material-UI in a React project <Grid container justify="center"> <Box className={classes.box}> <Grid item className={classes.item1}> <Typography variant="h5" c ...

What is the best way to link an anchor tag to a specific tab's content section

*Attempting to understand how to implement an anchor tag that will open a specific tab* *JavaScript code for navigation tabs* function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent" ...

CSS: Contain text within a div to dynamically adjust the div's length based on the text content

Check out this code snippet: View the Fiddle <div id="main" style="border:1px solid red;"> <div id="child" style="background-color:#68c5e7; width:170px; margin:0 auto; font-size:30px; background-image:url(https://www.google.by/logos/2012/javelin ...

The Unforeseen Consequences of Bootstrap Navbar CSS

I'm still learning CSS, so bear with me if I don't explain this issue correctly. Whenever I click on a navigation menu tab in Chrome or Safari, a mysterious blue rectangle appears. It doesn't show up in FireFox though. I'm not sure what ...

The MUI Grid design features information displayed on the left side, accompanied by an image placed directly to the right

In the React MUI V5 sample code below, I am creating a profile page layout with details of a person displayed on the left side of the page in label/value format. My question is how to position an "IMAGE" entry (assume it's a 300px x 300px profile ima ...

What is the most effective way to incorporate animated hyperlinks?

I've been grappling with a webpage I'm designing, featuring sentences acting as links arranged in inline-block format. My goal is to create an animated effect that resembles twinkling stars, pausing the animation on hover. It feels like I'm ...

Can a specific CSS rule be written in Material UI using makeStyles that will only apply if the element has both classes together?

It's common knowledge that achieving this in CSS is a possibility. .makeStyles-mainNavWrapper-67.sticky{ position: fixed; top: 0px; opacity: 1; transition: opacity 1s ease; padding: 10px; } I am curious to find out if this can be achieved ...

How can you stop the click event from firing when UI elements are stacked on top of each other in NextJs/React

I am struggling to find a solution in NextJs/React to prevent click events when UIs are layered, but I am confident that it can be done. Here is an example that works: https://i.sstatic.net/IYPNcUGW.png When you click ..., a floating menu UI should appe ...

What types of arguments are typically sent to the component prop within redux-form?

Recently, I came across some code in a redux-form based application that utilizes a custom renderer for a component. The Field definition used in this code snippet is as follows: <Field name="email" component={this.renderInput} type="email" val ...

Tips on changing the button ID within a class based on a condition in JavaScript?

Currently, I am utilizing ChartJS to create a pie chart where elements are added each time the user clicks on a specific button. There are 14 buttons in total that trigger the addition of a specific element to the pie chart. Each button activates a functio ...

Responsive menu not functioning properly with jQuery

I am currently working on a website located at . My goal is to incorporate the navigation plugin called MeanMenu into the site. I have followed all the instructions provided in the tutorial: adding the jQuery script to my HTML, including the CSS in the hea ...