I have used
html, body {
background-image: something;
}
in my CSS for many years. Now I can't remember why really..
Is that method even necessary/beneficial or is body {} enough?
If you're applying a background, selecting body is usually enough; the browser will know to paint the background over the entire viewport regardless of the body dimensions. The details of how a browser is expected to behave are covered in the spec (CSS2.1, CSS3 module). Even the CSS2.1 spec recommends it (although it doesn't mandate it for reasons mentioned later in the prose):
For HTML documents, however, we recommend that authors specify the background for the BODY element rather than the HTML element.
The only situation in which you would apply a background to both elements is when you want to layer one background over a different one; you could either use the CSS3 syntax of layered backgrounds on just the body element, or have body's background overlay that of html. Even then, the only reason I can think of for choosing the latter is if you need compatibility with older browsers that don't support the CSS3 syntax. I cover both methods in-depth in my answer to this related question.
Related
According to the spec:
It is recommended that authors of HTML documents specify the canvas background for the BODY element rather than the HTML element.
But it doesn't say what advantages it has. Why does the spec recommend this?
P.S. It crossed my mind when I saw Extra scrollbar when body height is 100vh: isn't it better to simply give the background to the html element instead?
Prior to CSS, backgrounds were specified by adding the background and bgcolor attributes to the body element in HTML (along with the likes of text, link, alink, vlink, leftmargin, marginwidth, topmargin and marginheight).
CSS-compliant browsers convert these presentational attributes into the appropriate style rules, placed as author-level presentational hints with just less precedence than author-level * rules. More on this in css-cascade-3 and HTML. Namely, the background and bgcolor attributes are converted to background-image and background-color declarations respectively, for the body element.
So, the recommendation that authors specify the canvas background for the body element and not the html element was made to ease migration of legacy HTML documents from presentational attributes on the body element to CSS. Normally if you have control of both the markup and CSS the first thing you'd probably want to do is get rid of the presentational attributes. But you don't have to do so right off the bat; you can just add a background declaration specific to the body element, and it will seamlessly replace the entire page background (as described in the spec link in the question) as specified by the presentational attributes, with no further action necessary:
/* The bgcolor attribute is equivalent to a
body {
background-color: #FFFFFF;
}
rule at this position in the stylesheet,
except with less precedence than a * rule.
The following rule will override it as a
normal part of the cascade. */
body {
background-color: yellow;
}
<body bgcolor=#FFFFFF>
<h1>Hello world!</h1>
<p>This page was once white...
<p>... now it's yellow!
If you add it to the html element instead, you'll end up with two backgrounds:
/*
body {
background-color: #FFFFFF;
}
*/
html {
background-color: yellow;
}
<body bgcolor=#FFFFFF>
<h1>Hello world!</h1>
<p>This page was once white...
<p>... wait, what?
If you're aware of the body element having a bgcolor attribute, this does have the advantage of serving as a visual reminder to you to get rid of the attribute. But if that doesn't occur to you right away, you'll probably be left flummoxed.
Of course, if you're authoring new documents then this simply becomes a matter of tradition (which ties in to the whole "ease of migration" thing). There's nothing stopping you from applying backgrounds to both html and body for interesting effects, though even that has largely been superseded by the ability to add multiple background layers to one element and is only really necessary if you need to support older browsers. More on this in the link above.
It is a matter of preference actually, this is why it is recommended rather than being forced as a strict rule.
The body tag being a descendant of the html tag overrides the html properties - being background otherwise.
However, since all browsers give a margin to body by default, creating a border between the body and the browser window (although we are used to resetting this margin to 0), I guess this ...border was meant to be visible, so using a background on the HTML would make this border invisible to users. Given this fact and since all content is contained inside the body tag, the recommendation was provided by spec.
However, nowadays the body tag is usually reset to 0 by almost everyone so using it on either html or body tag makes no difference and each case provides no advantages compared to the other.
My answer will be quicker, because BoltClock's one and the spec explain it minutely.
It is a matter of efficiency.
If you think about the fact that the UA should "[use the] values of that BODY element's background properties are their initial values", it makes sense to assign these values to the body tag.
If you use the html tag, UA may use a kind of fallback to display it, which is time consuming.
Of course, it's nothing for nowadays computers, but what about mobile devices, displaying let's said a background image with a cover background-size?
Furthermore, the order of html tags is a logical one, the link tags are defined in the head, in order to be used for the body and his childrens that come after. But if you apply a css rule to the html tag, the UA may go backward... And then forward.
So what are the advantages of specifying the canvas background for the BODY element? Quite nothing, for you, but some microseconds for the user, some microwatts for the client and the servers, but small streams make big rivers.
The w3c may have decided to do the opposite, it will have been ok too, it's just the purpose of a standard, that you make what a browser expects of you.
What? iOS does not respect the rules? (they can, they are apple). Don't change the correct way to do that, use media queries.
I plan on using some of the new HTML5 semantic elements, but it looks like some of them aren't well supported even on newer browsers (main isn't supported in IE11 as far as I can tell) is there a way to have them be treated as a <div> if they aren't supported, as the HTML5 semantic tags I plan on using are currently basically the same as divs AFAIK (header, footer, main are the ones I currently plan on using, also canvas but there isn't a good alternative tag to do what canvas does).
Currently if I use one of the unsupported tags in IE it seems to be treated as an unstyled tag but the issue is I can't set the width or height of it in css. What can I do for it to be treated as a and apply all styles that I put in css to that element using the name of the tag as the selector as though it were a <div>.
main
{
width: 100px;
}
does not work in IE11, if it was IE7 or something I wouldn't be too worried but quite a lot of people still use more updated versions of IE and I don't want the website to display improperly to them.
You need the HTML5 shim for supporting older browsers but using just the HTML5 shim does not fix IE11 see: http://jsfiddle.net/jbowyers/n3qZp/. So you also need a CSS reset that includes the 'main' element such as normalize. Or you can just add the CSS reset directly to your project as mentioned by others
main { display: block;}
The html5shiv will allow you to style the main element in IE 11 (and less). There's an explanation of what it does (actually a breakdown of its entire history) here.
Money quote:
Btw, if you want CSS rules to apply to unknown elements in IE, you
just have to do document.createElement(elementName). This somehow lets
the CSS engine know that elements with that name exist
NB. You should probably be using the shiv as a matter of course if you're using HTML5 and plan to support anything less than IE 9.
I think I have found a solution.
In my css file if I do:
main /*or any other unsupported tag that you want treated as a div*/
{
display:block;
other-property:other-value;
other-property:other-value;
...
}
It seems to act identical to a <div> tag. I haven't thoroughly tested or researched this solution (tested several attributes including color, width and text-decoration on IE11 and google chrome with tag named <asdasd> and it worked exactly like a <div>) so if anyone knows any problems with it please let me know.
I’m not sure what the question really is, but the title “Use <div> as backup tag for HTML5 semantic elements” is a good answer to the question “How can I use the HTML5 main, header etc. tags to that my page also works on browsers that do not support them?”
For example, instead of having just <main>...</main> in HTML and main { ... } in CSS, you would have
<div class=main>
<main>...</main>
</div>
in HTML and
.main { ... }
in CSS.
This may look redundant, and you get almost the same browser coverage by using polyfill like html5shiv and explicitly declaring main { display: block } if the polyfill doesn’t do that. But in this approach, you do all the styling in an old robust way and use the new elements only for their semantics. (In reality, the “semantics” means nothing, but maybe some day some programs will recognize main, article etc. and deal with them in some special way.)
I'm digging through some older code on a site that I'm working with, which uses iconize. The way that it seems to work is by adding a class like this...
a[href=$='.pdf']{
padding: 5px 20px 5px 0;
background: transparent url('icon.gif') no-repeat center right;
}
Is there any benefit to doing it that way than the way that I'd have done it? Something like this...
a[href=$='.pdf']:after{
content: url('icon.gif');
vertical-align: sub;
}
Here's a fiddle to demonstrate both of them...
JSFiddle
My question is... What are the benefits, if any, of using pseudo-elements vs. standard padding and background positioning for appending/prepending images to elements?
Just a few initial and later thoughts. I may still think of some more to add.
Padding/Background
Advantage(s):
Works for IE6-7 (i.e. older browsers).
If one wanted to overlap the icon with the text, especially if centered, this would be easier to implement.
Disadvantage(s):
More thought needed to implement (must calculate some factors).
For older browsers, only one background was supported, so if another background was needed, then there was a conflict to be resolved.
If browser is set to not print background images, then a "gap" for the padding will still exist in the printed text, but no image will be there. This could be resolved through print media css.
Pseudo-Elements
Advantage(s):
Easier to implement (no calculations needed).
It can have its own padding, border, opacity, etc. applied if desired, just as if it were a real element.
Related to #2, it can actually be moved outside the element if needed or desired.
Semantically, it is being implemented in a more appropriate manner. The icon is not really a "background," but neither is it an essential part of the html that a content img might be, so the pseudo-element fits the bill for enhancing the presentation, but not causing issues if it is missing (in older browsers).
In CSS3 browsers (and possibly CSS2), usually less code can be used to switch between right or left aligned icons (see "Discussion about code length" below).
Disadvantage(s):
Only one (of each type) allowed per element, so if it is needed for something else on an element, then you can have conflict.
Not supported in older browsers.
Some elements (replaced elements) cannot take pseudo-elements, so this would not even be an option.
Discussion about code length
EHLOVader noted in a comment to the question that part of his concern was extra coding that might be needed for pseudo-elements as opposed to background/padding if one wanted to switch to a left side icon. He gave this codepen example. However, it can be made to be less code to do a pseudo-element. Assuming .iconleft is a class used to put the icon left rather than right, and .iconit the class that sets an icon at all, then the following code concisely makes it happen for CSS3 browsers using the :not() selector (here is the fiddle, using the original .pseudo class of the OP for iconing):
.iconit:not(.iconleft):after,
.iconit.iconleft:before {
content: url('http://www.jasonapollovoss.com/web/wp-content/uploads/2010/09/pdf_icon_small.png');
vertical-align: sub;
}
The same could be done with CSS2 browsers if an iconright class is used to explicitly set an icon to the right, or iconleft to the left (no iconit class needed then):
.iconright:after,
.iconleft:before {
content: url('http://www.jasonapollovoss.com/web/wp-content/uploads/2010/09/pdf_icon_small.png');
vertical-align: sub;
}
What makes pseudo-classes so useful is that they allow you to style content dynamically. In the example above, we are able to describe how links are styled when the user interacts with them. As we’ll see, the new pseudo-classes allow us to dynamically style content based on its position in the document or its state
Read more http://coding.smashingmagazine.com/2011/03/30/how-to-use-css3-pseudo-classes/
Often times I see something like this:
<body>
<div class="container">
</div>
</body>
Why not just do:
<body class="container">
</body>
You are perfectly free to do any of the following:
add a class or id attribute to the body element;
directly apply CSS to the body element, with or without class or id attributes; or
directly apply CSS to the html element, although without the class or id attributes and with some important caveats.
Any of these are perfectly legitimate uses of CSS and HTML.
Why <div id="container"/>? Through the years, many CSS techniques have employed arbitrary container elements for conceptual simplicity, to avoid certain cross-browser inconsistencies or because they were simply too complex to be achieved otherwise. A couple of more subtle reasons include that in older browsers, one could not apply CSS to the html element directly, and there were (and are) certain unusual or restricted properties for those elements—often for obvious reasons. (They were sometimes described as being "magic" for this reason.)
These all conspired to create a situation where to achieve almost any moderately complex layout, it was inevitably much easier to just start out with a squeaky-clean container element. Though the practice started as a means to an end it soon became just part of the scenery, and now many developers don't think twice about adding that sprinkling of extra markup.
No, there is nothing that says you can't add a class to the body.
Attaching a class to the body is actually quite common in various CMSes and is very handy for theming or styling specific pages.
From looking at your example, if you just want to use the body as a container, why even bother with the class? There should only be one body element, so just call that in your selector.
Walter, it may make sense if you needed to apply a slightly different subset of styling to a page with a custom body tag.
Using a wrapping div is usually for some presentational reason and make not make sense semantically; if you don't need it for your project, don't use it. Sometimes only using the body tag to contain the page is too inflexible for some layouts, and as Jordan says some old browsers cannot apply CSS to the root element.
Background: I need to have an inline element to which I can apply width and height via CSS.
AFAIK, img is the only way to have this behavior, currently.
I would rather not have the image point to a transparent pixel GIF on the server. It may be cached, but browsers queue it nevertheless, slowing down overall page speed. Other clients might not be caching at all.
PS No, floating div is not sufficient, it behaves differently from inline elements.
EDIT Sorry, I should have inserted the term "cross browser" somewhere. It must at least be working for FF≥2, IE≥7 and current Safari.
You could use the "data:" URI scheme to embed an image.
Other replaced elements might also work. Setting display to "inline-block" might also be worth looking into.
Can you set:
display:inline-block;
width:50px;
height:10px;
IIRC, images are an "inline block" element, thus they can be rendered inline in text strings, but still have block-like properties.
I guess it will be valid in the W3C validator sense, because the validator does not check whether the link is a resource or not.
However, valid in the broader sense, I would say it is not. An src attribute is required in the IMG tag, and I would say must point to a valid image resource.
I find outis`s "data: URI" idea the best way.
If that doesn't work, a transparent image is your best bet. It's one call, it's a few bytes at best, and will be cached by most clients.
Using "about:blank" as src will cause IE to display red X-boxes. This line of CSS prevents this (in IE 8+), but it's still all a bit hacky:
img[src="about:blank"] {visibility:hidden}
You can accomplish the same thing with a tag.
<p style="height: 400px; width: 400px; background-color: #ffcccc;"> </p>
Height and width are settable. This should be across the common browsers, however I have not been able to test Safari or Chrome using it.
Use a <span> tag with a in it - totally valid - then set it's width and height in CSS, also apply display: block;
Using an empty <span> tag means it will be ignored by screen readers and it won't show up as a broken image when styles are disabled.
It'll also not use up any more bandwidth.
:-D