Friday, February 27, 2015

CSS - div #foo vs div#foo - How a space cost me an hour worth of frustration

I start "coding" again and quickly ran into the "pulling my hair out" moment on why I cannot troubleshoot the simplest of things. By "coding," I mean working on stylesheets. Yes, I have not even reached the real code stuff (yet I suppose I do have much fewer frustrations there because the syntax is more strict there).

So, I am working on a layout with a site div that contains many sub-divs which may also have additional sub-divs. I was able to get styles up quickly and easily, then I wanted to add a width to the highest parent of divs and for some reason it would not work. I tried all sorts of combinations of switching ids, spell checking, and checking other divs. It works for all the divs except the parent one.

Here is basically my layout:

 

 

   

 

 




And my style sheet:
div #foo { width: 800px; border: 1px solid black; }


No matter what I did, nothing happened, yet if I changed #foo to #top or any other id, I would have a banner. Then finally, I removed food and made it separate from the other divs completely. Suddenly, I had no borders at all except for left, content, and right.

This made me realize that having a space meant the sub-object of the previous object. In other words, CSS is looking for an object named foo inside of a div. Because foo is the parent div, there is no parent div thus CSS does not find a foo instead a div. This is why all the other divs changed accordingly because they were all within a div, foo (whether it was named or not).

So the proper way that I should have coded this was to remove the space between div and #foo, thus making it div#foo. All my problems went away! FINALLY! Nothing like this to remind how foolishly amateurish I can be.

Even #foo would work, but I thought I would be cool by being a little more specific. Even in hindsight, I should have known this because I have used similar practice with classes. Although, I admit that I actually didn't know this difference even though I have developed websites for several years. Usually, I have a placeholder div so I never ran into this problem but not realizing that was what kept all my designs working. Of course, I decided today to not do that because I just felt like making the design insignificantly more efficient.

As for searching on google, this was not easy to find because "css style not working" brings up a lot of results. And "css style working on all objects except parent" did not return what I was looking for. Defining this issue is still not simple even though I have figured out the problem. Perhaps, this problem is too easy to even be mentioned. Hopefully (or perhaps not), I am not the only person to run into this problem and this would help someone in the future........ perhaps my future self!