Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular button that resizes with window size

Tags:

css

resize

I'd like to make a circular button (div works too) and put it in the centre with a diameter of 20% of the height of the window. This I can do, but the button will become oval if the window isn't exactly square (I'd like the width and height to be the same - a 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 isn't much of an option as it wouldn't resize based on the window. Any ideas?

like image 581
Andrew Avatar asked Feb 19 '23 03:02

Andrew


1 Answers

There are two ways to achive this; with and without JavaScript.

The JavaScript method

Here's a simple demo: little 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 it isn't necessary):

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

The non-JavaScript (CSS) method

For a CSS-only solution, you need to use the fact that all padding values are calculated relative to the element parent's width, not height (reference). Little demo: little 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;
}
like image 95
Chris Avatar answered Mar 07 '23 15:03

Chris