I appreciate that I could just "try it and see", but I'd prefer to err on the side of caution here and ask if anyone has prior experience with this matter, or knowledge that would allow an answer ;)
I'm working on a feature that will include many elements (around 800) in a canvas-like container. All of these are <div> elements with a background-image. They will be aligned to a grid.
I have some ideas for neat animations that would involve transitioning elements to their new positions when some of them are added or removed - this would involve position:absolute and setting left and top appropriately.
I'd like to know how well browsers would handle this kind of thing, or if I would be better off just using display:inline-block and letting them flow as they would - no neat transitions, though.
In short I'm just wondering if the use of position:absolute, ie. removing the elements from the document flow, would be too much for the browser to handle when updating, as opposed to simply allowing the elements to exist in the flow of the document.
Does that make sense? I feel like I'm wording this horribly XD
If all of the elements will have the same height, then I'd just use display:inline-block or float:left, and they'll fit nicely together.
If the elements will have different heights, they will not perfectly "fall in line" when floated or displayed as inline-blocks.
For the latter, using a jquery plugin such as Masonry would be a sensible solution. Masonry uses the absolute positioning your question refers to, and no, it is not too much for the browser "to handle."
You can, of course, still use Masonry if your divs will have the same height.
Without a script solution like Masonry, I doubt it'd be a good idea to use absolute positioning on 800 elements to achieve your desired result.
Related
I have started getting into web development and have created a first draft for my website siavoush-re.co.uk, however the more research I do the more I realise the methods I have used for positioning is not good.
is positioning with margins better than using relative/absolute
positioning?
What is best practise when positioning elements, especially for responsive design?
What methods should I avoid using or are outdated?
Margins and paddings are better than positioning use % unit for responsive designs.
You can use position:relative; for the responsive design as BOOTSTRAP also use this positioning,but using absolute positioning will move your content when you view on a small device.
Avoid using pt or px unit for font-size, use 'EM'
Relative and absolute positioning isn’t bad per se, sometimes useful, but just incredibly easy to do wrong.
You want multiple columns. Traditionally, we use the float property for that, as legacy browsers support it well. There are a couple of new properties that will allow you to create columns as well, but legacy browsers do not support them, so for now I would personally discourage use unless you’re absolutely sure your visitors run modern browsers and you don’t care if the site fails on legacy browsers.
The Easy Way
Either way, floating in CSS is tough. I would highly recommend a responsive grid system. There are many CSS downloads available. All you have to do is use the appropriate classes for your columns.
Bootstrap: http://getbootstrap.com/ (comes with a lot of extras, so use with caution)
Skeleton: http://getskeleton.com/
Pure.css: http://purecss.io/
Responsive Grid System: http://www.responsivegridsystem.com/
There are tons more.
The Hard Way
By far, floating is the most popular choice. Floating elements causes block elements (like divs) to sit aside. You apply a width to each column, and voila, you have multiple columns. Doing sizing with gutters and paddings is slightly annoying, hence I recommend using an existing stylesheet that does it all for you. Basically, after several columns, you will have to append an element with the clear property to fix the layout flow.
Alternatively, depending on your target audience, you can use CSS columns, flexbox or grid.
Why Not Use Absolute/Relative?
Browsers sort out the flow for you. Growing elements will push down anything that comes after. Relative positioning doesn’t change this behaviour, but absolute positioning does. It just smacks the element on top of your stuff, and you will have to make room for you content yourself.
I do use relative/absolute positioning sometimes, but only to make things overlap. For example, I have an image container (relative), that holds an image (absolute) and a title/label (absolute). By having the latter two positioned absolutely, I can move within the container as I like. By setting a size on the container, I can put it anywhere I want without breaking the flow.
It depends, relative position is the positioning of elements
relative to the actual flow of HTML.
Whereas absolute positioning is in reference the the top-left coordinate of your document. (not always)
Best practices for responsive layouts?
There is nothing best, you must know when to use media queries and use % instead of px for columns widths and also float property.
Here you can find the list of depreciated properties and tags
Very nice work :)
You can investigate Bootstrap http://getbootstrap.com. I used it recently and with this framerowk you can do amazing responsive websites :) Simply add specified classes and styles to <div>, <span>, <p> and other HTML elements.
CSS resets help establish a baseline from which all the styles are set. A reset effectively overrides the browsers’ default styles for certain elements (which can vary greatly). Despite the popularity of CSS resets over the past several years, many sites still don’t employ them, and these sites’ CSS scalability is suffering greatly for it.
Instead of using the extremely popular CSS Reset by Eric Meyer (because it is too far-reaching) or making up a DIY reset, many people recommend using normalize.css. Normalize.css “normalizes” the code to a common baseline rather than resetting the base styling for elements across all browsers. Referring to the normalize.css project on Github, these are its advantages over a CSS reset:
Preserves useful defaults, unlike many CSS resets
Normalizes styles for a wide range of HTML elements
Corrects bugs and common browser inconsistencies
Improves usability with subtle improvements
Explains what code does using detailed comments
Using normalize.css in lieu of a standard reset will get you on the right coding foot and save a lot of time in not having to reestablish baseline styles.
enter link description here
To answer each of your questions in turn:
This really depends on the context of the element in the HTML and what you are trying to achieve in the site layout. Quite simply, there are often multiple solutions to a problem. Sometimes it is more appropriate to use margins, some solutions are best left to relative positioning, and other times absolute positioning is your only answer.
See 1 although I would avoid hard coding widths and heights in pixels: % and em are commonly used in responsive design. My best advice would be to follow a few tutorials and see how the CSS works together. The CSS media-design is often used in responsive web design.
Best to follow W3C recommendations for outdated HTML and CSS. From the top of my head, you should avoid using <table> tags to define site layout.
Interesting read: http://www.w3.org/TR/mobile-bp/
I'm experimenting with CSS and the float property. I have this "website", with a lot of divs aligned to 80px grid and float: left:
Is there a way in CSS to make it looking like this - so the elements can use empty space above them?
Without JavaScript, if it's possible.
Thanks, Martin.
No, this can't be done in CSS. Best way is to use a javascript item called masonry I'm afraid.
http://masonry.desandro.com/
For tiling dynamic content both horizontally and vertically, the CSS options are:
float:left, as you've already seen, only offers limited horizontal tiling.
display:inline-block gives a different result than float:left, but with no tiling.
CSS multi-column layout isn't fully defined yet. It supports vertical flow into implicit columns, but probably not in a way that qualifies as tiling.
flexible box layout isn't well supported yet. It supports a type of horizontal or vertical flow that might not qualify as tiling, though it feels like a step in the right direction.
In short, even the CSS standards that aren't fully defined yet don't seem to support this; so it may be a long ways off. The simplest fallback option is to use a jQuery plug-in.
Besides Masonry (as #Billy Moat suggested), another couple jQuery plug-ins are Isotope and Tiles Gallery. Masonry seems to be mentioned the most often.
lets say that the number of px to go up to fill the space of 1 block is 50px. margin-top: -50px;
It's not magic, it's only a bit manual to do that for each ones. If your content is dynamic, this could not work, or need js to calculate if we need to go up or not, on multiple rows and everything.
this can be done, but as CHE says, if your content is dynamic, this will go wrong in the worst possible ways.
But if it is a static site, this can be done, for sure.
To solve this, think in blocks & group and align them, inside each block re-align all blocks.
The new display:inline-block attribute seemed like a useful alternative to doing display:block + float:left/right, but the strange spacing/white-space behavior it introduces seems to negate that convenience.(See here and here) On top of that, browser support is spotty and needs fixes, though that will obviously change.
According to this Yahoo UI uses it heavily, but why? Is there a compelling case for using inline-block?
One useful situation is when you want to have rows of items with variable height. If you were to use floats, then you'd also have to come up with some way to clear all of the second row from the first. Here's an example of that ugly behavior.
But, using the magic of inline-block, here's a version that works. With only two additional CSS rules, it even works in IE6 and 7!
I usually use inline-block for inline elements that I want to be able to give height and width to. This is helpful when using sprites (especially for rounded corner buttons using the sliding door method). I don't use it for everything though and I'm more likely to actually use a float when needed than to break a block level element to using inline-block.
Because floats introduce issues in IE in terms of horizontal floats need an explicit width assigned in order to stay on the same horizontal level. With inline-block ( with fixes ) you can avoid assigning explicit widths to the floated items but maintain the blocky inline behaviour that you desire.
You also don't have to clear the items afterwards but I guess that compensates for the inline-block fixes you need to do.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I was developing a web page, where I was laying out a board for a Chess-like game, along with a couple of piece trays. It's all done using HTML (with jQuery for dynamic updating as the game is played). Somewhere I'd got the notion that using absolute positioning of elements within a page was considered a bad practice, and that it was preferable to use relative positioning.
After struggling with relative positioning for too long, I realized that absolute positioning of the board elements would be much, much easier to get right... and it was.
Is anyone aware of a reason that relative positioning is preferable over absolute? Are there any guidelines or rules of thumb that you apply when deciding which approach to take?
For a chess like game such as you are developing, there is nothing inherently wrong with using absolute positioning. As you said, relative positioning and normal flow layout make this sort of task quite difficult.
Of course, if you were developing a more standard website, such as a site providing some public service, absolute positioning overrides the default flow layout of browsers and so will reduce accessibility for many users. In this case I would avoid it.
Having said that, a lesser known benefit of absolute positioning is that it allows localized absolute positioning within the nearest "positioned" parent element.
Note: A "positioned" element can be any of the following: relative, fixed, absolute, or sticky.
To explain:
<div id="parentDIV" style="position:relative">
<div id="childDIV" style="position:absolute;left:20px;top:20px;">
I'm absolutely positioned within parentDIV.
</div>
</div>
Here, childDIV is actually positioned 20px from the left and 20px from the top of parentDIV, NOT the overall document. This gives a nice precise control over nested elements on a page, without sacrificing the overall page flow-layout.
So to answer your question (relative positioning being preferred over absolute): I don't believe there is a correct answer, it depends on what you are needing to build. However in general positioning (absolute or relative) versus default flow layout, my approach is as described above.
Keep in mind also that absolute positioning is not only used for positioning things relative to the browser window - it's also used for positioning things accurately within a containing element. When I finally understood this - after years of using CSS - it really revolutionized my ability to use CSS effectively.
The key is that an absolutely positioned element is positioned in the context of the first ancestor element that has position:relative or position:absolute. So if you have this:
div.Container
{
position:relative
width:300px;
height:300px;
background:yellow;
}
div.PositionMe
{
position:absolute;
top:10px;
right:10px;
width:20px;
height:20px;
background:red
}
and
<div class=Container>
...
<div class=PositionMe>
...
</div>
...
</div>
...the div PositionMe will be placed relative to Container, not to the page.
This opens up all sorts of possibility for precise placement in particular situations, without sacrificing the overall flexibility and flow of the page.
It does not answer your question, but...
For a chess like game board I think you can also use a table.
After all, it is is columns and rows you are displaying.
Now I know that many people start shouting 'don't use tables' and 'tables are evil'. Tables are however still a valid tool for showing some types of data, especially columns / rows organised data.
Look at your website in different browsers under the following conditions:
Switch your OS settings to high-dpi/large fonts/high contrast (all change the size of the default browser font)
Increase/decrease the default font size in the browser
Override the page fonts in the browser (usually somewhere in the Accessibility options)
Override/turn off the page stylesheet (granted, users shouldn't expect a chess game to work properly in this scenario :-))
In general absolute position is bad when you have inline elements with non-fixed size fonts. For your scenario it might work; however, there will be a lot of edge cases where something funky will go on.
I think the problem is that absolute positioning is easy to abuse. A coordinate system is much easier for lay people to understand than the box model. Also, programs like Dreamweaver make it trivially simple to layout a page using absolute positioning (and people don't realize what they're doing).
However, for typical page layout, the default static positioning should be adequate and get the job done 90% of the time. It's very flexible, and by keeping everything in normal flow, elements are aware of the other elements around them, and will act according when things change. This is really good when dealing with dynamic content (which most pages are these days).
Using absolute positioning is far more rigid and makes it difficult to write layouts that respond well to changing content. They're simply too explicit. However, it is perfect if you're in need of freely moving elements around a page (drag/drop), need to overlay elements on top of each other, or other layout techniques that would benefit from working on a coordinate system. Frankly, a chessboard sounds like a fine reason to use it.
Relative positioning is nice if you can pull a totally fluid layout because it will look reasonable on a large range of screen resolutions.
That being said, it's quite often to find (especially when trying for cross-browser compatability with older versions), that totally fluid layouts are hard to get right. Falling back on absolute positioning shouldn't be frowned upon, most mortal web developers do it all the time.
As long as you structure your HTML so that the elements follow a logical order that makes sense when rendered without CSS, there is no reason why using absolute positioning should be considered bad practice.
There are no hard and fast rules. The different forms of positioning are all good at different things.
The majority of work is usually best done with static positioning (it is the least fragile option), but absolute positioning is very good on occasion. Relative positioning, on the other hand, is something I've never used except for animation (on elements which are statically positioned until JavaScript gets involved), establishing a containing block for absolute positioning (so the element itself isn't moved at all), and (very very rarely) a one or two pixel nudge of an element.
Some things are impossible to do without position:absolute. Other things are WAY easier to achive with absolute positioning (let say that you want a bottom-right button for "read more" in a fixed/min height box and you don't have enough text in that box).
So, my advice: just use the one that fits your needs...
It seems to me like I'm the only one here that totally disagree with the assumption that absolute posititioning is not a bad practice
Except conditions like animation or elements that should specifically sit in an "unusual" place whitin their parents, absolute positioning break the structure of your HTML (which is exactly what HTML suppose to define in my opinion) because you can achieve results that differ the visuality from the structure very easily.
Moreover, implementation of design is way harder and problematic with absolute because you need to measure every element and you have lot of place to mistake (against normal flow that is much easier and right for structure building of a website skeleton)
And finally, regarding the chess board, I believe that the hardest possible way to create it is using position absolute!
Making the board with table would be much easier and right (after all this is a table)... And personally I would do it with a cube class that would have float: left (with clear on every ninth cube)
Absolute positioning of 64 different square is insane!
IMO, not a bad thing at all. I have recently completed an assignment with AA standards compliance and support for FF2, IE7, IE6 (yes, a pain I know). There were certain layouts which were only achievable because of absolutely positioning! Even certain components like buttons where layering was needed (transparencies) were possible only because of absolute positioning. If someone has a better way, please refer me to that.
Absolute positioning breaks the flow, if we know how to restrict the flow (change parent's coords to relative/absolute) it is fun. I don't know about older browsers (IE6 itself is a dinosaur) but one painful thing I found was, writing to PDF (Cute PDF) or opening with WINWORD (sue me) gives a shabby result.
Absolute positioning is a tool, like any tool, it can be used in good and bad ways. There is nothing wrong with it: StackOverflow probably uses it to display its alerts in the orange bar at the top of the site.
Now, in your situation, this is not bad either. But I think it would be much easier for you not to use it.
A chess board is a table, table cells don't need position tweaks. For events, onblur / onfocus and cie will do the job. Why would you even need pixels calculation?
So don't be stressed by the quality of your practice, but maybe you could check if you really need absolute positioning.
For example I have a situation where I have something like this (contrived) example:
<div id="outer" style="margin: auto>
<div id="inner1" style="float: left">content</div>
<div id="inner2" style="float: left">content</div>
<div id="inner3" style="float: left">content</div>
<br style="clear: both"/>
</div>
where there are no widths set on any elements, and what I want is #inner1, #inner2 and #inner3 to appear next to each other horizontally inside #outer but what is happening is that #inner1 and #inner2 are appearing next to each other and then #inner3 is wrapping on to the next line.
In the actual page where this is happening there is a lot more going on, but I have inspected all of the elements very carefully with Firebug and do not understand why the #inner3 element is not appearing on the same line as #inner1 and #inner2 and causing #outer to get wider.
So, my question is: Is there any way to determine why the browser is sizing #outer the way it is, or why it is choosing to wrap #inner3 even though there is plenty of room to put it on the previous "line"? Baring specific solutions to this problem, what tips or techniques do you hardcore HTML/CSS/Web UI guys have for a poor back end developer who has found himself working on the front end?
It would be nice to have a tool that could tell you exactly what all your layout problems are, but in this case the browser rendered the page exactly how it should have -- the combined width of the floats exceeded the width of the containing block, so the last one drops to a new line (this is slightly different than the IE6 expanding box/float drop problem which is typically caused by content inside the float, not the floats themselves). So in this case, there was nothing wrong with your page.
Debugging this is simply a matter of walking through your HTML in Firebug and figuring out which children of a block is exceeding the block's width. Firebug provides plenty of information for this purpose, although sometimes I need to use a calculator. I think what you described about being able to see which elements constrain other elements would simply be too complex and overwhelming, especially for elements that are removed from normal flow (such as floats or positioned elements).
Also, a deeper understanding of how CSS layout helps a lot as well. It can get pretty complicated.
For example, it is generally recommended to assign explicit widths to floated elements -- the W3C CSS2 spec states that floats need to have an explicit width, and does not provide instructions of what to do without it. I think most modern browsers use the "shrink to fit" method, and will constrain themselves to the width of the content. However, this is not guaranteed in older browsers, and in something like a 3-column layout, you'll be at the mercy of at the width of content inside the floats.
Also, if you're striving for IE6 compatibility, there are a number of float related bugs that could also cause similar problems.
Try the Web Developer Plugin for Firefox. Specifically, the Information -> Display Block Size and Outline -> Outline Block Level Elements options. This will allow to see the borders of your elements, and their size as Firefox sees them.
In Firebug's CSS tab, you can see what style rules apply to a selected elements in the cascading order. This may or may not help you in your problem.
My guess would be that something about the content of #inner3 is causing it to wrap below the first line, and the #outer is just getting sized to accommodate the smaller needed space.
So I found the answer in my specific case -- there was a div much further up in the DOM that had specific left/right margins set which compressed it and everything in it.
But the heart of the question is really how can you easily debug this sort of issue? What would be perfect in this case for example would be something in Firebug that, when hovering over an element's size in the layout panel would display a tool tip that says something like "width constrained by outer element X; height constrained by style Z on element Q" or "width contributed to by inner elements A, B and C".
I wish I had the time to write something like this, although I suspect it would be difficult (if not impossible) to get that information out of Firefox's rendering engine.