Michel
Michel

Reputation: 1153

Border box not working when width and height of a div is assigned through JavaScript?

I have <div> with border:1px solid red; and box-sizing:border-box;. The width and height of the <div> is assigned using JavaScript (so that user can switch from portrait to landscape).

$("#cloud").width(width).height(height);//width=260.16,height=397.44

The problem is that box-sizing property is not working. It always adds 2px(border) to the height and width of the div.

What I have tried:

  1. Assigned box-sizing using JavaScript, still not working.
  2. If we assign width,height and box-sizing using CSS, it's works fine.
  3. Tested in chrome and edge.

So how can I create a border-box div where user specifies the width and height?

Note: I'm writing all the Javascript inside the JQuery global function jQuery( function(){ .. });

Here is the JsFiddle https://jsfiddle.net/af1ohuxv/6/

Upvotes: 0

Views: 169

Answers (2)

Efkiss
Efkiss

Reputation: 115

You can approach it with .css() for example

$("#cloud").css("width","400")

or with array

$("#cloud").css({"width:"+width,"height:"+height})

https://jsfiddle.net/efkiss/af1ohuxv/12/

Upvotes: -1

31piy
31piy

Reputation: 23859

In the docs of width(), it is clearly stated that

Note that .width("value") sets the content width of the box regardless of the value of the CSS box-sizing property.

Same goes for height(). Not sure, what's the expected end result, but you wanted to use innerWidth() and innerHeight() (or outerWidth() and outerHeight()) instead:

$("#cloud").innerWidth(width).innerHeight(height);

Upvotes: 4

Related Questions