Jivan Shrestha
Jivan Shrestha

Reputation: 23

How can I define the width of one element based on another unrelated element?

I want to make a div 80% as wide as another div, but they are neither nested nor siblings.

How can I do this with SASS

Upvotes: 2

Views: 3788

Answers (1)

anpsmn
anpsmn

Reputation: 7257

You can use a variable for original width and use that for calculation of the width. I have used a mixin to show a demo with width both in pixels as well as percentages.

HTML

<div class="parent">
  <div class="three">three</div>
  <div class="four">four</div>
</div>
<div class="one">one</div>
<div class="two">two</div>

SCSS

@mixin calc_width($obj) {
    width: calc(0.8 * #{$obj})  
}


$width_in_px: 300px;
$width_in_percentage: 50%;

.one{
  width: $width_in_px;
  height: 50px;
  background: red;
}
.two {
  @include calc_width($width_in_px); 
  height: 50px;
  background: green;
  }

.parent {
  width: $width_in_px;
  background: orange;
}
.three{
  width: $width_in_percentage;
  height: 50px;
  background: lime;
}
.four {
  @include calc_width($width_in_percentage);  
  height: 50px;
  background: black;
  }

Updated Codepen

Upvotes: 2

Related Questions