1

I'm trying to make a calculation with a css property but it doesn't return anything.

I think it may be because the css property is returning '200px' rather than simply '200'. Can anyone suggest a work around? Many thanks.

windowHeight = $(window).height(); // This works
logoHeight = $('.home h1').css('height'); // This returns '200px'
logoPosition = windowHeight * 0.5 - logoHeight;
2
  • The value you request from css is a string containing 'px' you need to replace this via JS yuorself or parse the number. Commented Nov 14, 2011 at 11:59
  • 1
    Note that there are better ways to center something vertically than javascript. Commented Nov 14, 2011 at 12:19

4 Answers 4

5

You need to convert the "200px" string to an integer; using parseInt

windowHeight = $(window).height(); // This works
logoHeight = parseInt($('.home h1').css('height'), 10); // This returns '200px'
logoPosition = windowHeight * 0.5 - logoHeight;

Otherwise your sum windowHeight * 0.5 - logoHeight is returning NaN (not a number).

It is important to always specify the radix as the second parameter to parseInt, or you'll find things like;

parseInt("022") == 18; // true
Sign up to request clarification or add additional context in comments.

Comments

3

You should just be able to use height() on the <h1> element:

windowHeight = $(window).height(); // This works
logoHeight = $('.home h1').height(); 
logoPosition = windowHeight * 0.5 - logoHeight;

1 Comment

This is better than using css('height') because you make better use of jQuery
1

try this,

windowHeight = $(window).height(); // This works
logoHeight = $('.home h1').css('height'); // This returns '200px'
logoPosition = windowHeight * 0.5 - parseInt(logoHeight);

1 Comment

Thanks very much - this was the most useful just because it helps me understand the issue and how to put other CSS into an integer.
0

Here are some other examples to show you how to use other CSS properties and jQuery methods. Check our jQuery style properties

var element = $('#element');
var borderLeftWidth = parseInt(element.css('borderLeftWidth'), 10); // css border-left-width
var borderRightWidth = parseInt(element.css('borderRightWidth'), 10); // css border-right-width
var fullWidth = element.outerWidth(false); // includes padding and border but not margins

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.