11 Most Asked Questions About HTML
KiranPoudel98
Posted on August 21, 2020
HTML, Hypertext Markup Language, is the standard markup language used mainly for creating pages to display on World Wide Web (WWW). It is very simple, easy to learn, and allows you to create amazing websites. So, today we will be checking out the 11 most asked questions about HTML.
11 Most Asked Questions About HTML
1. Why does HTML think “chucknorris” is a color?
Answer:
It’s a holdover from the Netscape days:
Missing digits are treated as 0[…]. An incorrect digit is simply interpreted as 0. For example the values #F0F0F0, F0F0F0, F0F0F, #FxFxFx and FxFxFx are all the same.
It is from the blog post A little rant about Microsoft Internet Explorer’s color parsing which covers it in great detail, including varying lengths of color values, etc. If we apply the rules in turn from the blog post, we get the following:
- Replace all nonvalid hexadecimal characters with 0’s
chucknorris becomes c00c0000000
- Pad out to the next total number of characters divisible by 3 (11 -> 12)
c00c 0000 0000
- Split into three equal groups, with each component representing the corresponding color component of an RGB color:
RGB (c00c, 0000, 0000)
- Truncate each of the arguments from the right down to two characters
Which gives the following result:
RGB (c0, 00, 00) = #C00000 or RGB(192, 0, 0)
Here’s an example demonstrating the bgcolor
attribute in action, to produce this “amazing” color swatch:
<table>
<tr>
<td bgcolor="chucknorris" cellpadding="8" width="100" align="center">chuck norris</td>
<td bgcolor="mrt" cellpadding="8" width="100" align="center" style="color:#ffffff">Mr T</td>
<td bgcolor="ninjaturtle" cellpadding="8" width="100" align="center" style="color:#ffffff">ninjaturtle</td>
</tr>
<tr>
<td bgcolor="sick" cellpadding="8" width="100" align="center">sick</td>
<td bgcolor="crap" cellpadding="8" width="100" align="center">crap</td>
<td bgcolor="grass" cellpadding="8" width="100" align="center">grass</td>
</tr>
</table>
Why does bgcolor="chucknorr"
produce a yellow color? Well, if we apply the rules, the string is:
c00c00000 => c00 c00 000 => c0 c0 00 [RGB(192, 192, 0)]
Which gives a light yellow gold color. As the string starts off as 9 characters, we keep the second C this time around hence it ends up in the final color value. We originally encountered this when someone pointed out you could do color="crap"
and, well, it comes out brown.
2. How do you disable browser Autocomplete on a web form field/input tag?
Answer:
Firefox 30 ignores autocomplete="off"
for passwords, opting to prompt the user instead of whether the password should be stored on the client. Note the following commentary from May 5, 2014:
- The password manager always prompts if it wants to save a password. Passwords are not saved without permission from the user.
- We are the third browser to implement this change, after IE and Chrome.
According to the Mozilla Developer Network documentation, the Boolean form element attribute autocomplete
prevents form data from being cached in older browsers.
<input type="text" name="foo" autocomplete="off" />
Alternative Answer:
In addition to autocomplete=off
, you could also have your form field names be randomized by the code that generates the page, perhaps by adding some session-specific string to the end of the names. When the form is submitted, you can strip that part off before processing them on the server-side. This would prevent the web browser from finding context for your field and also might help prevent XSRF attacks because an attacker wouldn’t be able to guess the field names for a form submission.
3. How to change a class of an HTML element in response to an onclick
event using JavaScript?
Answer:
Modern HTML5 Techniques for changing classes
Modern browsers have added classList which provides methods to make it easier to manipulate classes without needing a library:
document.getElementById("MyElement").classList.add('MyClass');
document.getElementById("MyElement").classList.remove('MyClass');
if ( document.getElementById("MyElement").classList.contains('MyClass') )
document.getElementById("MyElement").classList.toggle('MyClass');
Unfortunately, these do not work in Internet Explorer prior to v10, though there is a shim to add support for it to IE8 and IE9, available from this page. It is, though, getting more and more supported.
Simple cross-browser solution
The standard JavaScript way to select an element is using document.getElementById("Id")
, which is what the following examples use – you can, of course, obtain elements in other ways, and in the right situation may simply use this instead – however, going into detail on this
is beyond the scope of the answer.
To change all classes for an element:
To replace all existing classes with one or more new classes, set the className attribute:
document.getElementById("MyElement").className = "MyClass";
(You can use a space-delimited list to apply multiple classes.)
To add an additional class to an element:
To add a class to an element, without removing/affecting existing values, append a space and the new class name, like so:
document.getElementById("MyElement").className += " MyClass";
To remove a class from an element:
To remove a single class to an element, without affecting other potential classes, a simple regex replace is required:
document.getElementById("MyElement").className =
document.getElementById("MyElement").className.replace
( /(?:^|\s)MyClass(?!\S)/g , '' )
/* Code wrapped for readability - above is all one statement */
An explanation of this regex is as follows:
(?:^|\s) # Match the start of the string, or any single whitespace character
MyClass # The literal text for the classname to remove
(?!\S) # Negative lookahead to verify the above is the whole classname
# Ensures there is no non-space character following
# (i.e. must be end of string or a space)
The g
flag tells the replace to repeat as required, in case the class name has been added multiple times.
To check if a class is already applied to an element:
The same regex used above for removing a class can also be used as a check as to whether a particular class exists:
if ( document.getElementById("MyElement").className.match(/(?:^|\s)MyClass(?!\S)/) )
Assigning these actions to onclick events:
Whilst it is possible to write JavaScript directly inside the HTML event attributes (such as onclick="this.className+=' MyClass'"
) this is not recommended behavior. Especially on larger applications, more maintainable code is achieved by separating HTML markup from JavaScript interaction logic.
The first step to achieving this is by creating a function, and calling the function in the onclick attribute, for example:
<script type="text/javascript">
function changeClass(){
// Code examples from above
}
</script>
...
<button onclick="changeClass()">My Button</button>
(It is not required to have this code in script tags, this is simply for the brevity of example, and including the JavaScript in a distinct file may be more appropriate.)
The second step is to move the onclick event out of the HTML and into JavaScript, for example using addEventListener.
<script type="text/javascript">
function changeClass(){
// Code examples from above
}
window.onload = function(){
document.getElementById("MyElement").addEventListener( 'click', changeClass);
}
</script>
...
<button id="MyElement">My Button</button>
(Note that the window.onload part is required so that the contents of that function are executed after the HTML has finished loading – without this, the MyElement might not exist when the JavaScript code is called, so that line would fail.)
JavaScript Frameworks and Libraries
The above code is all in standard JavaScript, however, it is common practise to use either a framework or a library to simplify common tasks, as well as benefit from fixed bugs and edge cases that you might not think of when writing your code.
Whilst some people consider it overkill to add a ~50 KB framework for simply changing a class, if you are doing any substantial amount of JavaScript work, or anything that might have unusual cross-browser behavior, it is well worth considering.
(Very roughly, a library is a set of tools designed for a specific task, whilst a framework generally contains multiple libraries and performs a complete set of duties.) The examples above have been reproduced below using jQuery, probably the most commonly used JavaScript library (though there are others worth investigating too).
(Note that $
here is the jQuery object.)
Changing Classes with jQuery:
$('#MyElement').addClass('MyClass');
$('#MyElement').removeClass('MyClass');
if ( $('#MyElement').hasClass('MyClass') )
In addition, jQuery provides a shortcut for adding a class if it doesn’t apply, or removing a class that does:
$('#MyElement').toggleClass('MyClass');
Assigning a function to a click event with jQuery:
$('#MyElement').click(changeClass);
or, without needing an id:
$(':button:contains(My Button)').click(changeClass);
4. How to store Objects in HTML5 localStorage?
Answer:
Looking at the Apple, Mozilla, and Mozilla again documentation, the functionality seems to be limited to handle only string key/value pairs.
A workaround can be to stringify your object before storing it, and later parse it when you retrieve it:
var testObject = { 'one': 1, 'two': 2, 'three': 3 };
// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
Alternative Answer:
A minor improvement on a variant:
Storage.prototype.setObject = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObject = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
Because of short-circuit evaluation, getObject()
will immediately return null
if key
is not in Storage. It also will not throw a SyntaxError
exception if value
is ""
(the empty string; JSON.parse()
cannot handle that).
5. How to make a div not larger than its contents?
Answer:
The solution is to set div
to display: inline-block
.
6. Is it <br>
, <br/>
, or <br />
in HTML 5?
Answer:
Simply <br>
is sufficient.
The other forms are there for compatibility with XHTML; to make it possible to write the same code as XHTML, and have it also work as HTML. Some systems that generate HTML may be based on XML generators, and thus do not have the ability to output just a bare <br>
tag; if you’re using such a system, it’s fine to use <br/>
, it’s just not necessary if you don’t need to do it.
Very few people actually use XHTML, however. You need to serve your content as application/xhtml+xml
for it to be interpreted as XHTML, and that will not work in old versions of IE – it will also mean that any small error you make will prevent your page from being displayed in browsers that do support XHTML. So, most of what looks like XHTML on the web is actually being served, and interpreted, as HTML. See Serving XHTML as text/html Considered Harmful for some more information.
Alternative Answer:
This quote from the HTML 5 Reference Draft provides the answer:
3.2.2.2 Void Elements
The term void elements is used to designate elements that must be empty. These requirements only apply to the HTML syntax. In XHTML, all such elements are treated as normal elements, but must be marked up as empty elements.
These elements are forbidden from containing any content at all. In HTML, these elements have a start tag only. The self-closing tag syntax may be used. The end tag must be omitted because the element is automatically closed by the parser.
HTML Example: A void element in the HTML syntax. This is not permitted in the XHTML syntax.
<hr>
Example: A void element using the HTML- and XHTML-compatible self-closing tag syntax.
<hr/>
XHTML Example: A void element using the XHTML-only syntax with an explicit end tag. This is not permitted for void elements in the HTML syntax.
<hr></hr>
7. What are valid values for the id attribute in HTML?
Answer:
For HTML 4, the answer is technically:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (“-“), underscores (“_”), colons (“:”), and periods (“.”).
HTML 5 is even more permissive, saying only that id must contain at least one character and may not contain any space characters.
The id attribute is case sensitive in XHTML.
As a purely practical matter, you may want to avoid certain characters. Periods, colons, and ‘#’ have special meaning in CSS selectors, so you will have to escape those characters using a backslash in CSS or a double backslash in a selector string passed to jQuery. Think about how often you will have to escape a character in your stylesheets or code before you go crazy with periods and colons in ids.
For example, the HTML declaration <div id="first.name"></div>
is valid. You can select that element in CSS as #first\.name
and in jQuery like so: $('#first\\.name').
But if you forget the backslash, $('#first.name')
, you will have a perfectly valid selector looking for an element with id first
and also having class name
. This is a bug that is easy to overlook. You might be happier, in the long run, choosing the id first-name
(a hyphen rather than a period), instead.
You can simplify your development tasks by strictly sticking to a naming convention. For example, if you limit yourself entirely to lower-case characters and always separate words with either hyphens or underscores (but not both, pick one and never use the other), then you have an easy-to-remember pattern. You will never wonder “was it firstName
or FirstName
?” because you will always know that you should type first_name
. Prefer camel case? Then limit yourself to that, no hyphens or underscores, and always, consistently use either upper-case or lower-case for the first character, don’t mix them.
A now very obscure problem was that at least one browser, Netscape 6, incorrectly treated id attribute values as case-sensitive. That meant that if you had typed id="firstName"
in your HTML (lower-case ‘f’) and #FirstName { color: red }
in your CSS (upper-case ‘F’), that buggy browser would have failed to set the element’s color to red.
8. How to vertically align text next to an image?
Answer:
Actually, in this case, it’s quite simple: apply the vertical-align to the image. Since it’s all in one line, it’s really the image you want to be aligned, not the text.
<!-- moved "vertical-align:middle" style from span to img -->
<div>
<img style="vertical-align:middle" src="https://placehold.it/60x60">
<span style="">Works.</span>
</div>
Tested in FF3. Now you can use flexbox for this type of layout.
.box {
display: flex;
align-items:center;
}
<div class="box">
<img src="https://placehold.it/60x60">
<span style="">Works.</span>
</div>
Alternative Answer:
Here are some simple techniques for vertical-align:
One-line vertical-align:middle
This one is easy: set the line-height of the text element to equal that of the container.
<div>
<img style="width:30px; height:30px;">
<span style="line-height:30px;">Doesn't work.</span>
</div>
Multiple-lines vertical-align:bottom
Absolutely position an inner div relative to its container.
<div style="position:relative;width:30px;height:60px;">
<div style="position:absolute;bottom:0">This is positioned on the bottom</div>
</div>
Multiple-lines vertical-align:middle
<div style="display:table;width:30px;height:60px;">
<div style="display:table-cell;height:30px;">This is positioned in the middle</div>
</div>
If you must support ancient versions of IE <= 7
In order to get this to work correctly across the board, you’ll have to hack the CSS a bit. Luckily, there is an IE bug that works in our favor. Setting top:50%
on the container and top:-50%
on the inner div, you can achieve the same result. We can combine the two using another feature IE doesn’t support: advanced CSS selectors.
<style type="text/css">
#container {
width: 30px;
height: 60px;
position: relative;
}
#wrapper > #container {
display: table;
position: static;
}
#container div {
position: absolute;
top: 50%;
}
#container div div {
position: relative;
top: -50%;
}
#container > div {
display: table-cell;
vertical-align: middle;
position: static;
}
</style>
<div id="wrapper">
<div id="container">
<div><div><p>Works in everything!</p></div></div>
</div>
</div>
Variable container height vertical-align:middle
This solution requires a slightly more modern browser than the other solutions, as it makes use of the transform: translateY
property. (http://caniuse.com/#feat=transforms2d)
Applying the following 3 lines of CSS to an element will vertically center it within its parent regardless of the height of the parent element:
position: relative;
top: 50%;
transform: translateY(-50%);
9. How to create an HTML button that acts like a link?
Answer:
HTML
The plain HTML way is to put it in a <form>
wherein you specify the desired target URL in the action
attribute.
<form action="https://google.com">
<input type="submit" value="Go to Google" />
</form>
If necessary, set CSS display: inline
; on the form to keep it in the flow with the surrounding text. Instead of <input type="submit">
in the above example, you can also use <button type="submit">
. The only difference is that the <button>
element allows children.
You’d intuitively expect to be able to use <button href="https://google.com">
analogous with the <a>
element, but unfortunately no, this attribute does not exist according to HTML specification.
CSS
If CSS is allowed, simply use an <a>
which you style to look like a button using among others the appearance
property (it’s only not supported in Internet Explorer).
<a href="https://google.com" class="button">Go to Google</a>
a.button {
-webkit-appearance: button;
-moz-appearance: button;
appearance: button;
text-decoration: none;
color: initial;
}
Or pick one of those many CSS libraries like Bootstrap.
<a href="https://google.com" class="btn btn-primary">Go to Google</a>
JavaScript
If JavaScript is allowed, set the window.location.href
.
<input type="button" onclick="location.href='https://google.com';" value="Go to Google" />
Instead of <input type="button">
in the above example, you can also use <button>
. The only difference is that the <button>
element allows children.
Alternative Answer:
You can also do as:
<button onclick="location.href='http://www.example.com'" type="button">
www.example.com</button>
Note that the type="button"
attribute is important, since its missing value default is the Submit Button state.
10. How to move an element into another element?
Answer:
You can use destination.appendChild(source)
;
onclick = function(){ destination.appendChild(source); }
div{ margin: .1em; }
#destination{ border: solid 1px red; }
#source {border: solid 1px gray; }
<!DOCTYPE html>
<html>
<body>
<div id="destination">
###
</div>
<div id="source">
***
</div>
</body>
</html>
11. How to create a checkbox with a clickable label?
Answer:
Method 1: Wrap Label Tag
Wrap the checkbox within a label
tag:
<label><input type="checkbox" name="checkbox" value="value">Text</label>
Method 2: Use the for
Attribute
Use the for
attribute (match the checkbox id
):
<input type="checkbox" name="checkbox" id="checkbox_id" value="value">
<label for="checkbox_id">Text</label>
Note: ID must be unique on the page!
Explanation
A label can include up to 1 input and omit the for
attribute, and it will be assumed that it is for the input within it.
Excerpt from w3.org:
[The for attribute] explicitly associates the label being defined with another control. When present, the value of this attribute must be the same as the value of the id attribute of some other control in the same document. When absent, the label being defined is associated with the element’s contents.
To associate a label with another control implicitly, the control element must be within the contents of the LABEL element. In this case, the LABEL may only contain one control element. The label itself may be positioned before or after the associated control.
Using this method has some advantages over for
:
- No need to assign an
id
to every checkbox (great!). - No need to use the extra attribute in the
<label>
. - The input’s clickable area is also the label’s clickable area, so there aren’t two separate places to click that can control the checkbox – only one, no matter how far apart the
<input>
and actual label text is, and no matter what kind of CSS you apply to it.
Demo with some CSS:
label {
border:1px solid #ccc;
padding:10px;
margin:0 0 10px;
display:block;
}
label:hover {
background:#eee;
cursor:pointer;
}
<label><input type="checkbox" />Option 1</label>
<label><input type="checkbox" />Option 2</label>
<label><input type="checkbox" />Option 3</label>
Alternative Answer:
Just make sure the label is associated with the input.
<fieldset>
<legend>What metasyntactic variables do you like?</legend>
<input type="checkbox" name="foo" value="bar" id="foo_bar">
<label for="foo_bar">Bar</label>
<input type="checkbox" name="foo" value="baz" id="foo_baz">
<label for="foo_baz">Baz</label>
</fieldset>
In Conclusion
These are the 11 most commonly asked questions about HTML. If you have any suggestions or any confusion, please comment below. If you need any help, we will be glad to help you.
We, at Truemark, provide services like web and mobile app development, digital marketing, and website development. So, if you need any help and want to work with us, please feel free to contact us.
Hope this article helped you.
Original Source: DevPostbyTruemark
Posted on August 21, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.