David Lee
David Lee

Reputation: 41

Evaluating percentages to pixels in SASS

Currently, I'm setting a variable to correspond to a circle's width and height, like so:

$circle-diameter: 70%;

.circle {
    width: $circle-diameter;
    height: $circle-diameter;
}

However, the circle's width becomes 70% of the parent element's width, and the height becomes 70% of the parent element's height, which yields an oval that is wider than it is tall. Ideally, I'd like to convert .circle-diameter to a fixed size and assign the circle's width and height to that fixed size. Is there a solution for this in CSS/SASS?

Upvotes: 0

Views: 579

Answers (2)

Yukulélé
Yukulélé

Reputation: 17072

You can use padding-top instead of height, it will work because padding is relative to parent width.

.circle{
  width: 70%;
  padding-top: 70%;
  /* height: 0; */
}

http://codepen.io/yukulele/pen/PzGgNM

Upvotes: 2

Emirhan Özlen
Emirhan Özlen

Reputation: 484

What you are looking for is to have a fixed ratio between width and height. For a circle tho, the width/height ratio is 1. There's a hacky way to accomplish that task. First I'd like to write a css class that always provides us a space that has width/height ratio of 1. To do so:

See Fiddle

Why this works? Because, If you use percentage based units on padding, It always be relative to element's width. See reference

Next I always like to use absolute hack to provide myself a workaround in that nicely 1/1 ratio square that we've create.

See Fiddle 2

Using position: absolute for our own good, we've created a element that has a fixed ratio and has a working width/height properties.

After It depends on what you need to do. In your case I've created a nice circle for to examine the situation.

See Fiddle 3

Working source code

**Css**

.ratio-1 {
  position: relative;
  width: 100%;
  padding-top: 100%;
  background-color: silver;
}

.im-something-has-some-width {
  width: 200px;
  border: 3px solid lime;
}

.space-provider {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}

.yay-i-have-a-square-field {
  // lets use it for our own goods!
  width: 100%;
  height: 100%;
  background-color: skyblue;
  border-radius: 50%;
}

Html

<div class="im-something-has-some-width">
  <div class="ratio-1">
    <div class="space-provider">
      <div class="yay-i-have-a-square-field">
      
      </div>
    </div>
  </div>
</div>

Upvotes: 0

Related Questions