Round button that resizes with the window

I want to make a circular button (div also works) and place it in the center with a diameter of 20% of the height of the window. This can be done, but the button will become oval if the window is not exactly square (I would like the width and height to be the same - perfect circle).

.circle { height: 20%; width: 20%; border-radius: 100%; font-size: 20px; color: #fff; line-height: 100px; text-align: center; background: #000 } 

Hardcoding a pixel value is not a great option since it will not resize depending on the window. Any ideas?

+4
source share
2 answers

There are two ways to achieve this; with and without javascript.

JavaScript Method

Here is a simple demo: a small link .

HTML:

 <div class = "circle"></div> 

CSS

 html, body { height: 100%; } .circle { border-radius: 1000px; background-color: rgb(0, 162, 232); } 

JavaScript (uses jQuery, but this is optional):

 function upd() { var h = $("body").height(); $(".circle").height(h / 5); $(".circle").width(h / 5); } upd(); window.onresize = upd; 

JavaScript-free method (CSS)

For a CSS-only solution, you need to use the fact that all padding values ​​are calculated relative to the parent element width , not height ( link ). Small demo: small link .

HTML:

 <div class = "wrapper"> <div class = "main"> </div> </div> 

CSS

 html, body { height: 100%; width: 100%; } .wrapper { width: 20%; display: inline-block; position: relative; } .wrapper:after { padding-top: 100%; /*1:1 ratio*/ display: block; content: ''; } .main { position: absolute; top: 0; bottom: 0; right: 0; left: 0; /*fill parent*/ border-radius: 1000px; background-color: rgb(0, 162, 232); /*I wanted it to look good :)*/ font-family: 'Arial', Helvetica, Sans-Serif; color: white; } 
+5
source

There is a way to achieve the ideal circle without using JS, it is to determine the specifications for the percentage. When the padding is applied as a percentage, it is applied as a percentage of the objects width , which means that if you set the width and height to 0 and give the object 20% fill, you end up with a circle that occupies 20% of the available width. However, you need to be creative in order to get things inside the circle.

 <style> html, body { width:80%; } .square { width:0%; height:0%; padding:20%; position:relative; left:25%;/*Position central*/ border-radius:100%; margin:auto;/*Position central*/ border:1px solid #000000; } </style> 
+3
source

Source: https://habr.com/ru/post/1434855/


All Articles