圆形按钮,可根据窗口大小调整大小

And*_*rew 4 css resize css3

我想制作一个圆形按钮(div也可以)并将其放在直径为窗口高度20%的中心.我可以这样做,但是如果窗口不是正方形的话,按钮将变成椭圆形(我希望宽度和高度相同 - 一个完美的圆形).

.circle {
  height: 20%;
  width: 20%;
  border-radius: 100%;
  font-size: 20px;
  color: #fff;
  line-height: 100px;
  text-align: center;
  background: #000
}
Run Code Online (Sandbox Code Playgroud)

硬编码像素值并不是一个选项,因为它不会根据窗口调整大小.有任何想法吗?

Chr*_*ris 5

有两种方法可以达到这个目的; 有和没有JavaScript.

JavaScript方法

这是一个简单的演示:小链接.

HTML:

<div class = "circle"></div>
Run Code Online (Sandbox Code Playgroud)

CSS:

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

JavaScript(使用jQuery,但没有必要):

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

非JavaScript(CSS)方法

对于仅支持CSS的解决方案,您需要使用以下事实:所有padding值都是相对于父元素计算的width,而不是height(引用).小演示:小链接.

HTML:

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

    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)