Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax: Use variable for css value

Tags:

Trying to keep a box centered vertically within another box. I know there's css that can do this, but I'd rather use jquery, more reliable(?).

var textH = $(".Text").height(); var vertAlign = ((140 - textH)/2);  $(".Text").css({     marginTop: 'vertAlign' }); 

Not sure what detail I'm missing. The output should be half the available vertical space, in pixels.

EDIT

Originally, the text block was a span contained by a div. The div had a set height (140 px in this case), and the text block, the span, would be variable height based on how much text was in it. However, I need this text block to be editable. So I changed it to a text area. however, the behavior for the dimensions of the text area is awkward, and I had to set a static height and width to it. Now the height of this text block isn't variable, so there's no difference in height between it and it's parent with which to derive the margin-top spacing from. What should I do?

like image 477
C_K Avatar asked May 12 '11 04:05

C_K


People also ask

How do you set a variable value in CSS?

To declare a variable in CSS, come up with a name for the variable, then append two hyphens (–) as the prefix. The element here refers to any valid HTML element that has access to this CSS file. The variable name is bg-color , and two hyphens are appended.

Which is most correct syntax to use CSS variable?

Syntax of the var() Function The var() function is used to insert the value of a CSS variable. Note: The variable name must begin with two dashes (--) and it is case sensitive!

Can we use VAR in CSS?

The var() CSS function can be used to insert the value of a custom property (sometimes called a "CSS variable") instead of any part of a value of another property.

How will you declare a custom property in CSS?

The @property “at-rule” in CSS allows you to declare the type of a custom property, as well its as initial value and whether it inherits or not.


2 Answers

Remove quotes surrounding vertAlign

$(".Text").css('margin-top', vertAlign); 

Try the above code. It must help you.

like image 137
Arman P. Avatar answered Sep 20 '22 07:09

Arman P.


optionally if you'd like to do more than one style:

var styles = {'margin-top':vertAlign,'property':100,'property':somevalue} $(".Text").css(styles); 
like image 39
robx Avatar answered Sep 21 '22 07:09

robx