Proper way of styling HTML elements - html

I know you can do this:
<img style="position: absolute;" src="test.png" alt="Test image" width="50" height="50" />
I don't use this first method, because I know external stylesheets are meant to seperate the CSS from the HTML code. And I like to keep it that way.
<img id="foobar" src="test.png" alt="Test image" width="50" height="50" />
Sometimes I use this method, but when I look at some of the professional HTML coding of big sites like Facebook, Instagram or Twitter I see that they use a lot of container divs, which makes me unsure whether I'm doing it right or not.
<div id="foobar">
<img src="test.png" alt="Test image" width="50" height="50" /> //use 'src' in place of 'sc'
</div>
I found that I mostly use this method for some reason I actually don't really know. But in this case I just add styling to the div and not directly to the img. Or when I do, I directly add styling to the img element by selecting it with #foobar img{ ... } in the CSS.
<div id="foo">
<img id="bar" src="test.png" alt="Test image" width="50" height="50" />
</div>
Usually I do it this way if a container is just necessary to get the job done, where I would have some styling on the img and some on the div#foo element.
I know there probably are more ways, but it's mainly these last two methods I'm not too sure about when to use them. I know there are other HTML elements out there but I just took a div and img for demonstration.
With that being said, I would like to know what are the pros and cons of each and which method should be a good practise?

Many unnecessary tags creates a problem known as "Tag Soup" (ref). This is an issue in hand-written HTML; your goal is to use CSS styling to the maximum potential and obviate the need for excess and meaningless tags.
When creating a document "properly", you ought to start from a document outline perspective. Imagine the page is a report, and it will be read top-to-bottom, and is left-aligned and simple in style. You design this hierarchy with a minimum of markup, making full use of the header, section, article, and footer tags. In the "old days", you would use divs instead.
Next, you apply style to affect the appearance, including the positioning of elements in the document relative to one another. This is where any non-semantic divs can be added, to facilitate positioning and organization within the box model. Again, you still try to keep wrapping or non-semantic tags to a minimum.
Taking all that into account, often, large sites will not be composed of a clean and strictly semantic document outline. Most often, these sites are assembled by code, constructing dynamic bits of content into the overall page. In these scenarios, more non-semantic wrapping tags are often involved as a byproduct of modular, self-contained code generating fragments of HTML. Further, web applications may necessitate wrapping tags to aid in dynamic content redrawing via AJAX or other javascript actions.
Where CSS comes in to play is also a factor in adding non-semantic wrapping tags. Because of CSS specificity (magic!), it is occasionally desired to have some extra "handles" you can use to get really, really specific on a particular tag combination.
The take-away is to write the cleanest, most semantic code you can manage in your project. Beyond being minimal and semantic, there isn't a "proper way", per se.
Further Reading
Semantic HTML - http://en.wikipedia.org/wiki/Semantic_HTML
How Important Is Semantic HTML? - http://www.vanseodesign.com/web-design/semantic-html/
About HTML semantics and front-end architecture - http://nicolasgallagher.com/about-html-semantics-front-end-architecture/
"What are the benefits of using semantic HTML?" - What are the benefits of using semantic HTML?
CSS Specificity: Things You Should Know - http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/

In my opinion there is no absolute answer.It depends on your design.
If you have a lot of similar sections in your site that you want to style the same, you should use the div container (or other elements such as <nav>, <header> etc...).
The advantage of this method is that you can style other elements inside the section without giving each one a class attribute or id, thus, making you code cleaner and easier to maintain.
If you want to style a unique element I thing it's best to use the id attribute and add the CSS to this id.
Remember that id is unique, so, if you have two elements in the same page that will have the same CSS you'll have to duplicate your CSS code and it's never a good idea.

Main Reason for using style sheets is the ability to cache it in websites thus making load time faster once initially loaded. The reason why you see some elements with styling on the html itself maybe because its injected via server side code or by client side script. Where that part of code is literally invisible to FB developers and they would instead be seeing only a few lines of server code, so on their side it might not mean much as to how styling is done whether each element is addressed on style sheet or on html itself.
Another Reason might be when there is too much styling done with many classes on top of each other (nested classes) the final option may be to use it on the html element itself as it takes highest precedence and overrides any styles done by classes or any other form.
Many Reasons to use styles that way but generally its easier for developers to keep clean html/css/script and if possible separation but when things get complicated there comes a time when breaking the normal practice actually makes it easier...

Related

What is the purpose of the 'figure' tag in html?

I'm using the <figure> tag like this:
<!DOCTYPE html>
<html>
<body>
<figure>
<img src="img.jpg" alt="image" width="204" height="220">
</figure>
</body>
</html>
But if I remove the <figure> tag it doesn't appear to make any difference. Can someone explain to me what the use of the figure tag is?
The <figure> element is intended to be used in conjunction with the element to mark up diagrams, illustrations, photos, and code examples (among other things). The spec says this about <figure>:
W3C
The figure element represents a unit of content, optionally with a caption, that is self-contained, that is typically referenced as a single unit from the main flow of the document, and that can be moved away from the main flow of the document without affecting the document’s meaning.
MDN
The HTML <figure> element represents self-contained content, frequently with a caption <figcaption>, and is typically referenced as a single unit. While it is related to the main flow, its position is independent of the main flow. Usually this is an image, an illustration, a diagram, a code snippet, or a schema that is referenced in the main text, but that can be moved to another page or to an appendix without affecting the main flow.
Good question.
It all goes down to a few things - semantic meaning, SEO, accessibility (and maybe more…)
What is it?
The element is a semantic tag that just came out in HTML5. This tells the browser that is a container that holds elements that have a relation to each other. The plays a role to this and it will be explained below.
Also, note that it does not have to contain just element, it can contain other elements such as tables, video clip, audio clips, etc
Why should we use it?
Before HTML5, there was no element for captions for images, diagram, video and so on.
It will have a semantic meaning now with element. The will help the search engine to find these images.
And with semantics, your SEO improves and the bots will find your image faster on search engine with it and show it in results.
Accessbility
With figure and figcaption tags, the user (visually-impaired user) will be able to understand the structure (with the help of the screen reader).
The screen reader bot will inform the user that this is a caption content, so if it is placed right after or before the related images, the user will be able to understand it.
Answer inspired by: https://forum.freecodecamp.org/t/why-use-the-figure-element/315116/3
The reason to use a tag is because it is HTML5 semantic. It does not have class traits assigned to it. As the other answers have noted, you can remove it or replace with a div and it really wont change anything.
However if you are writing good 'semantic' code, which defines meaning in its tags then this is one of the standard tags you would include.
It is similar to or and other semantic tags which define your code in readable way to the browser and to the developer.
The whole point of the <figure> tag is that it is part of the main flow and if removed, it would not affect the flow of the document (source http://www.w3schools.com/tags/tag_figure.asp)
That's why it is mainly used for images, videos, animations etc...
Basically, you can look at it as wrapping tag that doesn't affect the position of its children

Semantic classes in Bootstrap

First of all, I apologize that this is probably a basic question, I tried searching other topics for an answer, but I'm still unsure.
I submitted a project where I needed to build a basic portfolio page using Bootstrap. I lost points for the following line of code:
<div class="container">
You need to add semantic tags. A semantic element clearly describes its meaning to both the browser and the developer. You can read more here: http://www.w3schools.com/html/html5_semantic_elements.asp
I understand why we should be using semantic tags however if I change the class from container to anything else it will adjust all the margins on the page. It was my understanding that Bootstrap recognized "container" and automatically applied Bootstrap properties to its children.
Am I doing anything wrong? Or am I just supposed to make a CSS rule that will apply margins to whatever I change container to?
Any help would be greatly appreciated, errors like this will become compounded with further projects!
I believe you are confusing tags and classes slightly: <div> is a tag - more specifically an element - and .container is a class. You can place the .container class on any element you want.
<p class="container"></p>
There are no definitive rules for class names, and as such they are not really a part of semantics, or SEO. A general suggestion is that they simply describe the element, not the styles.
Wherever you submitted your project most likely wanted to see a <section>, <article>, <aside> or some other HTML5 purely semantic element, which may or may not be proper semantics - kind of depends on what's inside it, and where it lies relative to the rest of the markup.
Generally speaking, the .container class is usually applied to generic elements in Bootstrap, and <div> is usually perfectly reasonable.
Another thing to consider, w3schools is a historically low quality source for web information, and usually a good indication that whomever is linking to it doesn't know very much about the web. I'd advise you to just start reading the tutorials and articles over at MDN, you'll learn a lot faster.

What to use instead of div elements in HTML5

I read in the HTML5 specification that the generic div tag should only be used as "last resort," when a more specific element is unavailable. For example, the tags header, footer and section are preferred for grouping content thematically.
But it seems like the vast majority of websites still use div as the primary element. My question is, how often and in what contexts is it appropriate to use a div? And which other elements should be used in its place?
I'm looking for answers based on the specification rather than personal opinions. Thanks!
There isn't anything that takes the place of <div> (theres a reason its still in the spec), but HTML5 has more elements available that are more specific.
In addition to <header>, <footer>, and <section> there is:
<nav>
<article>
<aside>
<main>
<details>
<summary>
<figure>
<dialog>
<menu>
and more!
Basically any new HTML5 element can take the place of a <div>.
When should you use a div? You answered it yourself:
when a more specific element is unavailable
MDN has a HTML5 element list which contains all standard HTML5 elements, and indicates which elements are new with HTML5.
The thing to remember is that div tag is still a part of HTML5 and it’s not obsolete, yet.
However, div element has been abused a lot with HTML4, and rightfully so as there were never any alternates to it. Now that HTML5 has included some great new structural elements, div is no longer the best option for creating layouts.
The main disadvantage with div is that the element has no meaning due to which creating application-ready layouts is very difficult. The new structural elements introduced in HTML5 will surely help a lot with that issue.
The section element will most likely be used more than the other structural elements like header, footer etc. mainly because it is not specific as others. Also there is no limit as to how many structural elements you can add but the thing to remember is that section is not a complete div replacement.
div still has a role in HTML5. It is great for grouping similar elements as well as dividing elements as needed. Also section should not be used just for styling because section was not intended to be a wrapper.
The reason header, section, footer, and other such elements were created is to help with referencing them in css and scripting languages. W3C looked at the most common IDs web developers were using for divs and made the new elements in HTML5 accordingly. The reason divs and IDs is widely considered bad practice is because all those attributes clutters up the code. And as we all know, cluttered coding leads to mistakes and errors.
Where do you use them? That's pretty self explanatory. Take the header for example. It's most common use is the top of the web page. Right click on the stack overflow logo at the top and view the source. They're actually using a div with an ID of 'header'. Technically, that's bad practice.
A great use for divs is to create a wrapper around your entire content like this.
<div id="wrapper">
<!--content-->
</div>
Then you can reference it in css to center:
#wrapper{margin:20px auto;}
Hoped this helped!

Assign a class name to <img> tag instead of write it in css file?

I am curious to know, is it true that it is better to assign a class name to the <img> tag in the html file instead of writing it down directly into css file?
<div class="column">
<img class="custom-style" alt="" />
<img class="custom-style" alt="" />
<img class="custom-style" alt="" />
</div>
instead of
.column img{/*styling for image here*/}
I need to know is there any differences between of these in terms of web performance?
UPDATE:
I'm sorry, supposely the question is multiple <img> tags inside the .column div and all the images are using the same styling.
The short answer is adding a class directly to the element you want to style is indeed the most efficient way to target and style that Element. BUT, in real world scenarios it is so negligible that it is not an issue at all to worry about.
To quote Steve Ouders (CSS optimization expert) http://www.stevesouders.com/blog/2009/03/10/performance-impact-of-css-selectors/:
Based on tests I have the following hypothesis: For most web sites,
the possible performance gains from optimizing CSS selectors will be
small, and are not worth the costs.
Maintainability of code is much more important in real world scenarios.
Since the underlying topic here is front-end performance; the real performance boosters for speedy page rendering are found in:
Make fewer HTTP requests
Use a CDN
Add an Expires header
Gzip components
Put stylesheets at the top
Put scripts at the bottom
Avoid CSS expressions
Make JS and CSS external
Reduce DNS lookups
Minify JS
Avoid redirects
Remove duplicate scripts
Configure ETags
Make AJAX cacheable
Source: http://stevesouders.com/docs/web20expo-20090402.ppt
So just to confirm, the answer is yes, example below is indeed faster but be aware of the bigger picture:
<div class="column">
<img class="custom-style" alt="appropriate alt text" />
</div>
It's just more versatile if you give it a class name as the style you specify will only apply to that class name. But if you exactly know every .column img and want to style that in the same way, there's no reason why you can't use that selector.
The performance difference, if any, is negligible these days.
Assigning a class name and applying a CSS style are two different things.
If you mean <img class="someclass">, and
.someclass {
[cssrule]
}
, then there is no real performance difference between applying the css to the class, or to .column img
Its depend. If you have more than two images in .column but you only need some images to have css applied then its better to add class to image directly instead of doing .column img{/*styling for image here*/}
In performance aspect i thing apply class to image is better because by doing so css will not look for possible child image.
I think the Class on img tag is better when You use the same style in different structure on Your site. You have to decide when you write less line of CSS code and HTML is more readable.

Is a wrapper <div> a violation of content-style separation?

It's been said that the goal of CSS is to provide visual presentation and the goal of HTML is to provide structure of the document. Well, thank goodness. It has gotten so much easier, especially compared to font tags!
But in practice, it seems that way many of us still rely on HTML to use CSS when it shouldn't be there. For example, it's common to see a <div id="wrapper"> to wrap around elements inside so the body can be centered. In pure HTML, it would never be used because it's meaningless and it's used ONLY for CSS.
Right? So doesn't using <div id="wrapper"> actually violate one of the fundamentals of content-presentation separation?
Kind of. But it doesn’t matter.
Principles like “separate content and presentation” are helpful because they help you achieve your goals, by making code easier to change. They’re not like nuclear safety regulations — contradicting them won’t risk anyone dying, so “violation” is a bit of a strong word.
Sticking in a wrapper <div> to work around the limitations in CSS (and/or browsers) is fine. <div> and <span> are intended for that very use, as they're defined to not convey any meaning (i.e. they don't alter the "structure" of the document). It doesn’t hurt the code.
If you can avoid it, great. But don’t worry if you can’t. There are bigger fish to fry.
In any case "wrapper" is a bad choice for an id. In general, wrapping DIV's are not used for simple alignment tasks alone (use a SPAN otherwise) and do provide/determine a structure for your web page. Therefore, in my opinion, wrapping DIV's do not violate the content-presentation separation.
You can use something like:
<div id="content_container">
<div id="section_container">
<h2></h2>
<p>stuff</p>
</div>
</div>
And I believe this gives correct structure to your document. Though it would probably be nicer to have elements for this (like <content> and <section>), because id can only be meaning full for us not for parsing the document. div have no actual meaning it's just a container for block elements that's all and so I believe it cannot violate content-presentation separation.
Having said all that you could also use <body> element to center your content (it is an element after all), but I'm not 100% sure if it work in old IE (old meaning IE 6).
If your DIV's ID has an exact equivalent in HTML5 (div id="nav", for example) then it's structural and, therefore, perfectly acceptable. div id="wrapper" is probably the equivalent of div id="article" or div id="section", so it's probably OK, although poorly-named, as Anzeo suggests.
It can do, though sometimes the div provides structure. We have to accept that CSS is not yet perfect and that compromises have to be made in our HTML. In particular in this case, when all browsers support the CSS3 pseudo-element ::outside ( http://www.w3.org/TR/css3-content/#wrapping ) I think that many wrapper divs will become unnecessary.
My personal opinion is wrappers have a very useful and necessary purpose although I dont use the term wrapper. Consider a div that has a set width of 200px but we want a border without effecting the width of the div we would need this solution:
div#posts {
width: 200px;
height: 200px;
}
div#posts-inner {
padding: 10px;
border: 1px solid #ccc;
}
<div id="posts"><div id="posts-inner">
<p>My Posts</p>
</div></div>
If you markup your CSS effectively you can avoid examples of less useful css declarations like:
#posts {
border: 1px solid #ccc;
}
If you put your CSS elements into context rather than assuming what its class represents
div#posts-wrapper {
border: 1px solid #ccc;
}
This would improve the separation of design and content elements in your css.
It's best to think of this in terms of semantics. You should be using the right tag for the right part of your part. HTML5 is a big step in this direction allowing the use of more tags such as 'article', 'nav' and 'section', which are give more semantic meaning than div.
However, div was a godsend for designers because it gave you a simple, block-level element with little semantic meaning other than to provide a 'divider', or 'section' of a page (much like the 'section' tag in HTML5). Not having anything else, it is perfectly acceptable to use in even a semantic sense because we didn't have anything else that had the same meaning and provided the same default characteristics.
It certainly doesn't violate the separation of style and content because it provides CSS with a block to do something with. You couldn't create most layouts on the web without using it AND keeping to a semantic structure!
It's common to see a "DIV
id='wrapper'" to wrap around elements
inside so the body can be centered. In
pure HTML, it would never be used
because it's meaningless and it's used
ONLY for CSS.
Is a containing wall not a structural piece of a building? I would argue that a containing wall is in fact one of the most common structural pieces you can find in elements.
So doesn't using DIV id=wrapper
actually violate one of the
fundamentals of content-presentation
separation?
No, A containing element (or a <div id="wrapper">) is just as much the structure of a document as a <header> <nav> <body> or <article>.
Even if it weren't considered structural, the goal of unobtrusive design is to separate as much as reasonably possible structure (HTML) from style (CSS) and behavior (JavaScript). In the end, unobtrusive design is really just a set of best-practice guidelines to follow to create more maintainable code.
Breaking the rules wont invalidate your code, and often times breaking the rules can create better, more maintainable code. As you design more and more, you will quickly learn that you sometimes have to go against the grain and ignore best-practices.