1

When I use jQuery to get a css property via:

$(selector).css("min-height");

The value that is returned is always a pixel value, even though I'm using "vw" units in the CSS, for example:

https://jsfiddle.net/darrengates/3yqt3nrj/

How can I get the ACTUAL CSS value (in vw) was was entered in the stylesheet?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Darren Gates
  • 473
  • 2
  • 18
  • 1
    It is possible to [parse the CSS stylesheet itself.](https://stackoverflow.com/questions/3326494/parsing-css-in-javascript-jquery) Question is, are you sure you need to? You can always convert pixels back to vw units by taking `$(window).width()` and doing a little math. – Blazemonger Jun 05 '17 at 20:02

1 Answers1

1

Two way you can do it.

1st (pure CSS) give a name to your CSS rule as the following so when you get the class you know what kind of CSS are applied:

.width_25vw {
  width: 25vw;
}

.min-height_25vh {
  min-height: 25vh;
}

.bg-red {
  background: red;
}

2nd You can always calculate to get vh vw or % if you want:

var mh = Math.ceil(parseFloat($('.min-height_25vh').css("min-height")));
var wh = $(window).height();
console.log(mh + 'px');
console.log(wh + 'px');
console.log(mh/wh*100 + 'vh');

Note Math.ceil here because StackOverflow does not return correct px value. (You can also check the example here: https://jsfiddle.net/dalinhuang/07s1t5qw/)

Also, you can get the raw CSS loop through style sheet but that's expansive. (REF: How to get a style attribute from a CSS class by javascript/jQuery?)

var mh = Math.ceil(parseFloat($('.min-height_25vh').css("min-height")));
var wh = $(window).height();
console.log(mh + 'px');
console.log(wh + 'px');
console.log(mh/wh*100 + 'vh');
.width_25vw {
  width: 25vw;
}

.min-height_25vh {
  min-height: 25vh;
}

.bg_red {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="width_25vw min-height_25vh bg_red">
</div>
Dalin Huang
  • 11,212
  • 5
  • 32
  • 49