2

What's a simple way to do this in CSS?

selector {
    width: 75%;
    height: width; 
}

I've tried set the height to various properties, but they don't seem to accomplish what I want. How can I set one value to the value of another?

GusP
  • 2,454
  • 2
  • 23
  • 32
Robby Bennett
  • 133
  • 1
  • 9
  • You can't use variables like 'width' in vanilla CSS. If you want to use dynamic values, see the [calc](https://developer.mozilla.org/en-US/docs/Web/CSS/calc) function. – K. S. Apr 14 '15 at 02:02
  • Are you looking for something like this : http://stackoverflow.com/q/5445491/1004522? – Ebad Masood Apr 14 '15 at 02:03
  • I think you need something like SASS or LESS to use variables. You could do it with JavaScript but not sure you can with vanilla CSS. – GusP Apr 14 '15 at 02:05
  • Yep, I found the answer. http://stackoverflow.com/questions/5445491/height-equal-to-dynamic-width-css-fluid-layout – Robby Bennett Apr 14 '15 at 02:05
  • Using JS is possible - but not the best way. See my answer for a much better, pure CSS solution. K.s. and GusP are wrong., it IS possible with pure css. – Scott 'scm6079' Apr 14 '15 at 02:07

4 Answers4

2

Padding-top percentages are based on width, so it's easy to calculate using pure CSS.

.wrapper {
  width: 50%;
  /* whatever width you want */
  display: inline-block;
  position: relative;
}
.wrapper:after {
  padding-top: 100%;
  /* 1:1 ratio, set from padding top being 100% */
  /* If you wanted one half as high, use 50% */
  
  display: block;
  content: '';
}
.main {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  
  /* fill parent */
  background-color: red;
  
  /* let's see it! */
  color: white;
}
<div class="wrapper">
  <div class="main">
    This is a sample 1:1 responsive DIV. 
  </div>
</div>
Scott 'scm6079'
  • 1,517
  • 13
  • 25
2

You can't currently in css except in firefox with CSS variables

http://caniuse.com/#feat=css-variables

You can use a dynamic stylesheet language like less or sass to write css with variables. You can then compile the code into plain css.

Example in less:

@size: 75%;
selector {
   width: @size;
   height: @size; 
}
Rebzie
  • 213
  • 2
  • 10
0

Well, if you know width = 75%, you could just say height = 75%.

selector {
    width: 75%;
    height: 75%;
}

Now if you change width using PHP/Javascript, just change height, too. This appears to be the simplest way to me, but I'm still pretty new to making websites.

This is also answered here: stackoverflow.com/q/5445491/1004522

Cody Richardson
  • 157
  • 3
  • 16
0

The easiest way i see is to use jquery in a way such as this:

<html>
 <head>
  <script>
   selector{
    width: 75%;
   }
  </scipt>
 </head>
 <body>
  <script type="text/javascript" src="/jquery.js"></script>

  <selector></selector>
  <script type="text/javascript">
   $("selector").css("height", $("selector").width());
  </script>
 </body>
</html>

To my understanding, this should make both width and height 75%.