What‘s the difference between setting [<div style=“width:;” onclick=”] to Width: 0;, and setting it to the exact width of the div style?

You are being confused here because all of your divs are the same size and in the same place. You can make it easier to see what is going on if you put a border around your divs. In the first div try style=“width:50px; border:1px solid #000;” then, in the cyan div set the left margin to margin-left:20px; You can now see that the divs overlap. When you click the first div both of these divs are replaced by the third hidden div.

In the second instance, where you set the first div width to zero, make the same changes to the border and the margin. You will see that the first div has no width and the only overlap is at the left hand edge. Again, clicking the div replaces both of the first two divs.

The second coloured div in both cases is not needed. You can get the same result by setting the width and height and background colour of the first div and removing the second div. This will simplify your code and make it easier to understand.

As a general rule it is far better to avoid mixing your style information and your HTML. Try setting a style class for the divs rather than using the “style” attribute. All of your CSS style information can then be in one place, rather than all over your page. This will help if you need to change a style and will lead to cleaner more understandable code. The same comment can be made for your onclick handlers; try to keep these in the JavaScript area of your page and out of your HTML. There are many references to these issues on the internet, so keep reading.:slight_smile:

1 Like