I am trying to set the width and height of a div in javascript but it is not being set. I have tried a lot but nothing is working. Here is what i have tried,
<div id="d1">asdasd</div>
<script>
var d = document.getElementById("d1");
d.style.width = "100px";
d.style.height = "100px";
d.style.cssText = 'border:1px solid black;'
</script>
Please check what is the problem!
I think d.style.cssText overwrites width and height properties
Try this:
var d = document.getElementById("d1");
d.style.width = "100px";
d.style.height = "100px";
d.style.cssText += 'border:1px solid black;'
As karaxuna mentioned, your d.style.cssText
is overwriting the width and height settings. Simply changing your code to either this:
var d = document.getElementById("d1");
d.style.width = "100px";
d.style.height = "100px";
d.style.border = '1px solid black';
or this:
var d = document.getElementById("d1");
d.style.cssText = 'border:1px solid black;'
d.style.width = "100px";
d.style.height = "100px";
works perfectly.
This works:
<div id="d1" style="border:1px solid black;">asdasd</div>
<script>
var d = document.getElementById("d1");
d.style.height = "200px";
</script>
An alternate would be to define a new style element in CSS and simply set d.className to that css element.
I guess d.style.cssText is problem
Your problem is with d.style.cssText = 'border:1px solid black;'
. it is overriding the width and height set by JS .
Check this fiddle:-
Change sequence of your JS statements it will work ie
<script>
var d = document.getElementById("d1");
d.style.cssText = 'border:1px solid black;'
d.style.width = "100px";
d.style.height = "100px";
</script>
Better put width, height properties in style attribute only. ie
d.style.cssText = 'border:1px solid black; width:100px; height:100px'
or in CSS class
d.style.cssText = 'border:1px solid black;'
d.style.float="left";
d.style.width = "100px";
d.style.height = "100px";
You neeed to use float:left attribute.
I don't know what your problem is but I've used this and this worked
function fnc1()
{
document.getElementById("d1").style.width="100px";
document.getElementById("d1").style.height="100px";
document.getElementById("d1").style.backgroundColor="red";
}
HTML:
<div id="d1">asdasd</div>
Javascript
document.getElementById('d1').style.height = 90+'px';
working demo here ( works fine with chrome, din't check with other browsers )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.