Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Behaviour when changing the size of a button

I’m working on creating a toggle switch. I want it to be responsive in case i’d like to resize it in the future. The toggle switch has a red square in it (for demonstration) and the problem is that when i change the width and height of the toggle switch, the red square stretches and changes its dimensions. What I’d like it to do is to keep its shape and to not have it moving around no matter how big or small the toggle switch is.

Here’s a demonstration:

width: 9em;
height: 4.5em;

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

/*half the size*/    
width: 4.5em; 
height: 2.25em; 

enter image description here

The red square becomes a rectangle for some reason and moves to the left.
Below is how I want it to look like when I change the width and height
(a.k.a exactly the same, just smaller)

enter image description here

I’ve tried percentage, vh, min-width, max-width, em, rem, px and the list goes on. Any ideas?

* {
    box-sizing: border-box;
}
button {
/*the height is 50% of the width*/
    width: 9em;
    height: 4.5em;
    border-radius: 100px 100px;
    border:none;
    padding-left: 1em;
}

.switch {
    display: block; 
    width: 40%;
    height: 70%;
    background-color: red;
}
<!DOCTYPE html>
<html>
    <head>
        <link href="style.css" rel="stylesheet">
    </head>
    <body>
            <button>
                 <span class="switch"></span>
            </button>
    </body>
</html>

>Solution :

If you want to keep the aspect ratio of 1:1, you should try the trick of using the same value for width and padding-bottom, as you can read in this answer here: How to style a div to be a responsive square?

Here is your modified example:

* {
  box-sizing: border-box;
}

button {
  /*the height is 50% of the width*/
  width: 18em;
  height: 9em;
  border-radius: 100px 100px;
  border: none;
}

.switch {
  display: block;
  height: 0;
  width: 35%;
  padding-bottom: 35%;
  margin-left: 10%;
  background-color: red;
}
<!DOCTYPE html>
<html>

<head>
  <link href="style.css" rel="stylesheet">
</head>

<body>
  <button>
                 <span class="switch"></span>
            </button>
</body>

</html>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading