Jump to content
KenBrace

How to do CSS width calculation with jQuery

Recommended Posts

The CSS "calc()" function is great for giving an element a width based on a percentage of its parent's width plus or minus a certain amount of pixels.

 

Example

 

 

.this_class {
width: calc(100% - 10px);
}

 

The above example gives the element a width of 100% of its parent width minus 10px.

 

But the "calc()" function doesn't work across all browsers yet (i.e. Opera). So how can this be solved?

 

Using jQuery is the answer. Below is a code example of how to do accomplish this.

 

 

<div id='parent'>
<div id='child'>
 
</div>
</div>

 

Let's say I want the div with an ID or "child" to be 90% of its parent width, plus 20px. You can do this with the following jQuery code...

 

 

$("#child").css("width", $("#parent").width() - 10% + 20px);

 

In the above example I first accessed the "child" element's css width property.

 

I then set the width by accessing the width of the "parent" and then subtracting 10% and adding 20px.

 

Hope this helps!

Share this post


Link to post
Share on other sites

Good to know, never knew about the CSS calc function, is that new in CCS3?  Is it used often?  Never seen it.

 

Yeah it's new to CSS3 and only works in select browsers. It's extremely useful though so we'll see it supported across all browsers before long. At the moment you still have to use jQuery if you want it to work cross-browser.

Edited by KenBrace

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...