Get the size of an HTML element
I am spending a couple of hours trying to get the width of my div container. I've read a lot of questions and answers, but none of them seem to work in my case - I always got 0. Finally, I found I could get it through a property scrollWidth
that wasn't even mentioned in this question and the like. Now I have what I wanted, I still don't know how it works.
Why don't all the other methods work? Why is it calledscrollWidth
? I don't want to scroll through anything - it's so confusing. Can I get the size of the element before adding it to the document - even scrollWidth doesn't work in this case. Is there a model that I have to follow in order to always get what I see on the screen? I don't see any patterns right now, I write something, watch something different on the screen and get something even bigger in the output. Every time I want to do something, it looks like there are 10 different methods that I can use, but usually it only works one or two because it depends on which methods I have used before. When I work with 2nd graphics I had x, y, width and height, but in html I always got this clever CSS that seems to know better what I want to do. Sorry if this sounds a little officious, but I'm a little annoyed,when I need to spend so much time on such a trivial task. I am using painting on canvas and it was much easier, but now I want to create a simple website, so it probably isn't a good idea to create one.
Here is my example
I understand that I am getting size 0 because these properties are relative to the element regardless of its children, and my container is 0.0 in size, right? I read that if I set a style display: inline-block;
it will adapt the size to automatically fit its children - why doesn't that work?
source to share
The container element actually has no width. This is why you get zero width. This can be seen if you use the dev tools item inspector.
This is because the container element is absolutely positioned and has no set width. Your children do the same position: absolute
, and so they won't force the container element to "grow" to their size.
To get the visible width of the menu, you can sum the widths of all children (first level menu items). This is probably the best approach to use for the way you are currently setting things up. Otherwise, I would suggest completely changing your approach with the html elements you use to the CSS properties you use to position the elements where you don't want them to be used position: absolute
.
I would suggest you open up your dev tools item inspector and start watching how everything reacts when you change position from "absolute" to "relative".
Understanding how to position elements and how width / height affects with CSS will save you tons of headaches - just like you do now :)
source to share