Derp Derp - 7 months ago 31
HTML Question

Aspect-ratio circle inside square div

I'm trying to make something like this in HTML/CSS: https://gyazo.com/6db0d2e3565414c10b65480c5d4b7526

I'm using a bootstrap template which I want to make this work with. My best try so far is the following piece of code:

<td class="tablerow mdl-data-table__cell--non-numeric"
style="background-color:red;padding:0 !important">

<div style="background-color:green;
border-radius: 100%;
width:auto;
height:100%;">
</div>
</td>


Which gives me this: https://gyazo.com/dab11409ae41f9deb69418d10d74d2c5

How can I make this a perfect circle, no matter what the lengths of the sides of the outer div are?

Edit

The problem is that the width and height of the outer
td
gets calculated at run-time by javascript by my template. Sometimes its 20px, other times its 50px for example, depending on the users screen. I need to have a circle, that always stays circular (maintaining aspect-ratio) no matter what the dimensions of the
td
are.

Answer

So what you are asking for I do not believe possible with CSS only (if you want it to maintain responsive) In order to do that you will need something like below:

<div id="wrapper" class="visible-square">
  <div id="square" class="square">
    <div class="content">
    </div>
  </div>
</div>
.visible-square{
  border: 1px solid #000;
  width: 300px;
  height: 200px;
}

.square {
  position: relative;
  width: 100%;
}

.square:after {
  content: "";
  display: block;
  padding-bottom: 100%;
}

.content {
  position: absolute;
  width: 100%;
  height: 100%;
    -moz-border-radius: 50%;
    -webkit-border-radius: 50%;
    border-radius: 50%;
  background: red;
}

$(document).ready(function(){
    var width = $("#wrapper").width();
  var height = $("#wrapper").height();
  if(width > height){
    $("#square").width(height);
  }
});

https://jsfiddle.net/qn21dvom/

How does this works:

The circle will stay perfect as long as the width is less than the height. The javascript comes in only when width is more than the height, and then what it does it sets the width of the child to be the height of the element.

You can update the javascript to make it on resize if this is meant to be a responsive element. Anyhow, above will do the trick when you don't know the size of the wrapper div.

Comments