Best html questions in June 2012

Is it possible to make a div 50px less than 100% in CSS3?

132 votes

Is it possible to make a div 50px less than 100% in pure CSS? I want the <div> to be only 50px less than 100%. I don't want any JavaScript.

Yes you can. Without using the IE's expression(), you can do that in CSS3 by using calc().

div {
    width: 100%;
    width: -webkit-calc(100% - 50px);
    width: -moz-calc(100% - 50px);
    width: calc(100% - 50px);
}

Demo: http://jsfiddle.net/thirtydot/Nw3yd/66/

This will make your life so much easier. It is currently supported in the 3 main browsers: Firefox, Google Chrome (WebKit), and IE9: http://caniuse.com/calc

MDN: https://developer.mozilla.org/en/CSS/-moz-calc

Which DOM elements cannot accept an id?

12 votes

I'm reading this basic tutorial on canvas elements. The (almost) in the following sentence caught my eye:

The id attribute isn't specific to the element but is one of the default HTML attributes which can be applied to (almost) every HTML element

Which html elements cannot accept an id?

In HTML5, the id attribute is a global attribute and can be specified on any element.


If you look through the Document Type Declaration for HTML4, you can find the elements which do not have %attrs; defined in their attribute list to indicate they do not support the id attribute. Those included are near the bottom in the "Document Head" section: HEAD, TITLE, BASE, META, STYLE, SCRIPT, and HTML.

Note that although the PARAM element does not include the %attrs; declaration in its attribute list, it does explicitly allow the id attribute itself in that list.

<!ATTLIST PARAM
  id          ID             #IMPLIED  -- document-wide unique id --
  name        CDATA          #REQUIRED -- property name --
  value       CDATA          #IMPLIED  -- property value --
  valuetype   (DATA|REF|OBJECT) DATA   -- How to interpret value --
  type        %ContentType;  #IMPLIED  -- content type for value
                                      when valuetype=ref --
  >

HTML/CSS: "See Through Background" Text?

11 votes

Ok, is this possible.

I have a background image. On top of that, I have a transparent grey box for content. I'd like to have title at the top in text, that is basically the letters exposing the background. So, the text removes the grey box and lets the background show through.

The only hacky way I can see is create an image with the letters transparent on a background the same grey color, and then try to somehow align that with the grey box.

Is there another - better - way?

One way is to use -webkit-background-clip: text;: demo here (webkit only obviously).

Using position, we can sync both backgrounds:

#container, #container h1 {
    background: url(bg.png)
}

#container {
    position: relative;
}

#container #gray {
    background: rgba(0,0,0,.8);
    padding-top: 8em;
}

#container h1 {
    font-size: 8em;
    padding-top: /* padding + border of div */;
    position: absolute;
    -webkit-text-fill-color: transparent;
    -webkit-background-clip: text;
}​

Or you could use the same approach and apply a svg mask, that will work in all modern browsers.

Rendering box shadow around unconventional shapes with HTML/CSS

11 votes

I'm currently working on a little project in which I'm trying to create a venn diagram representing additive colors. I've started with three circles (border-radius: 50%;) and used a combination of statically-position elements with hidden overflow to create some of the more complex shapes where the circles overlap. You can see what I currently have here:

http://jsfiddle.net/GjvEE/

One feature I'd like to add is the addition of a colored box-shadow around the shape currently being moused-over. The unique challenge I'm facing is presented by the nesting of the elements with hidden overflow, and the need to create 'faux-edges' along which to render the box shadow for each section of the diagram. I've considered the option of simply scrapping this approach and creating the shapes via SVG, but I'm interested to see if any of you have any clever ideas for building this sort of interaction into more complex shapes using traditional HTML and CSS3 alone.

Thanks in advance!

How about using CSS's :after to generate new circles behind the others and use a radial gradient background that fades to transparent?

I've done quick, basic implementations for Webkit on the red and blue circles here. Note the :hover:after style definitions. http://jsfiddle.net/stevelove/2hpwp/

Can I override inline !important?

10 votes

If you have

<div style="display: none !important;"></div>

Is there a way to override that in the stylesheet to make it displayed:

div { display: block !important; }

?

You can not override inline CSS having !important, because it has higher precedence, but using Javasctip/Jquery tweaks you may achieve what you want.

Mouseover event doesn't granulate on IE9 for sub elements, event doesn't start on IE8

9 votes

We were adapting a method posted here highlight a DOM element on mouse over, like inspect does to NOT use jQuery.

We came up with this solution so far: http://jsfiddle.net/pentium10/Q7ZQV/3/

This seams to work on Chrome and Firefox, but doesn't work as expected on IE.

  1. On IE9 for example the highlight doesn't occur on minor elements like the tag line eg: javascript, html, dom or the top line like: chat, meta, faq

    When I mouse over the javascript tag the big div is highligthed and this is wrong and it should be like we see in Firefox

  2. On IE8 and 7 it doesn't start, so that is another problem we need to fix

It turns out that in IE, elements that have no background (i.e. background: transparent) and the Gradient filter set do not receive mouse events. Demo

This is a happy coincidence, since you're using a RGBa background colour for your overlay and one of the workarounds for RGBa colours in IE is the Gradient filter.

By setting these styles on the overlay (for IE):

background: transparent;
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#7F000000,endColorstr=#7F000000)"; /* IE8 */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#7F000000,endColorstr=#7F000000);   /* IE6 & 7 */
zoom: 1;

mouse events pass through the overlay and onto the underlying elements, so inner / minor elements are highlighted correctly.

Other issues that are present in IE7/8:

  • When using element.attachEvent, the event name needs to be prefixed with "on":

    document.body.attachEvent('onmouseover', function(e) { ... })
    
  • To find the target of the event, you need to access event.srcElement instead of event.target.

  • As rodneyrehm mentioned, Array.indexOf isn't supported.

So here's a version of your solution that also works in IE 7-9: http://jsfiddle.net/jefferyto/Q7ZQV/7/

(BTW The highlighting is wrong for inline elements that span more than one line, e.g. the "ask your own question" link in the "Browse other questions..." line.)

Applying a background to <html> and/or <body>

8 votes

http://jsfiddle.net/julien_c/GmAL4/

I found that if you apply a CSS background to body, it takes up the whole page (no matter what the actual height of body is).

However, if you apply a CSS background to both html and body, the background for body does not take up the whole page.

Is this discrepancy expected behavior?

How would I go about superimposing two fullscreen backgrounds (say, a background color and a semi-transparent image?)

This is correct behavior.1 Unlike html, body doesn't immediately take up the entire height of the viewport, even though it appears so when you only apply a background to the latter. In fact, the html element will take on the background of body if you don't give it its own background:

For documents whose root element is an HTML HTML element or an XHTML html element: if the computed value of ‘background-image’ on the root element is ‘none’ and its ‘background-color’ is ‘transparent’, user agents must instead propagate the computed values of the background properties from that element's first HTML BODY or XHTML body child element. The used values of that BODY element's background properties are their initial values, and the propagated values are treated as if they were specified on the root element. It is recommended that authors of HTML documents specify the canvas background for the BODY element rather than the HTML element.

To that end, you can easily set a background color to html, and set a background image to body which you wish to superimpose over the background color. To ensure the background image on body takes up the full viewport height, you need to apply height and min-height respectively as well:

html {
    height: 100%;
    background-color: #ddd;
}

body {
    min-height: 100%;
    background: transparent url(background.png) center top no-repeat;
}

My comments under this other answer explain, with an accompanying fiddle, how body is actually offset from html by default margins even though it looks like it's being padded out instead, again owing to this seemingly strange phenomenon.


1 This may have its roots in setting the HTML background and bgcolor attributes of body causing the background attribute to apply to the entire viewport.

<html> width is less than its background

8 votes

I've set a style on <html>:

html {
    background: #ECECEC;
    border: 1px solid #FFFFFF;
}

If the contents of the page are wider than the page, why does the border stop, but the background keep going?

html is a proper block-level element, just like body, p, div, etc — it therefore observes all the same overflow rules as other block elements do.

However, the reason why the background of html bleeds past its border when content overflows its width (or when its width is less than 100% of the browser window, or viewport), is because the background color is propagated to the viewport, which is the canvas containing html and all its contents that are rendered. The border remains part of the html element, however, so the element doesn't expand when the content overflows. This behavior is very similar to how applying a background to body, but not html, causes the body background to propagate to the root element anyway, as described in this answer which cites this section of the spec.

As Alohci notes in a comment under the answer, the same applies to html with respect to the viewport:

Note that html behaves with respect to the viewport in much the same way as body behaves with respect to html, with the background escaping beyond the confines of the html element. See http://jsfiddle.net/GmAL4/4/ to see what I mean.

How can I style a part of a single character with overlays using a dynamic width?

7 votes

Question

Can I style just a part of a single character?

Meaning

CSS attributes cannot be assigned to parts of characters. But if you want to style only a certain section of a character, there is no standardized way to do that.

Example

Is it possible to style an "X" which is half-way red and then black?

Expected result

Not working code

<div class="content"> 
    X
</div>
.content {
    position: relative;
    font-size: 50px;
    color: black;
}

.content:after {
    content: 'X';
    color: red;
    width: 50%;
    position: absolute;
    overflow: hidden;
}

Demo on jsFiddle

Purpose

My intention is styling the Font Awesome icon-star symbol. If I have an overlay with dynamic width, shouldn't it be possible to create an exact visualization of scores?

While playing around with a demo fiddle, i figured it out myself and wanted to share my solution. It's quite simple.

First things first: The DEMO

To partly style a single character, you need extra markup for your content. Basically, you need to duplicate it:

<​div class="content"> 
    <span class="overlay">X</span>
    X
</div>

Using pseudo-elements like :after or :before would be nicer, but i didn't found a way to do that.

The overlay needs to be positioned absolutely to the content element:

​.content {
    display: inline-block;
    position: relative;
    color: black;
}

​.overlay {
    width: 50%;
    position: absolute;
    color: red;
    overflow: hidden;
}​

Do not forget overflow: hidden; in order to cut off the remaing part of the "X".

You can use any width instead of 50% which makes this approach very flexible. You can even use a custom height, other CSS attributes or a combination of multiple attributes.

Extended DEMO

Why is the source code for some web pages all in one line?

7 votes

When viewing lots of webpages' source code (like JS,CSS,HTML), I find them in one line. How did they make this? Do they use some tools to make it? Can we restructure it?

Thanks.

Using Minify technique

Some free tools also available

http://developer.yahoo.com/yui/compressor/

http://www.minifycss.com/minify-tools/minify-css-tools.php

http://jscompress.com/

http://www.minifycss.com/css-compressor/

http://code.google.com/p/htmlcompressor/

It combines multiple CSS or Javascript files, removes unnecessary whitespace and comments, and serves them with gzip encoding and optimal client-side cache headers.

Why is <INPUT> wider than i told it to be?

7 votes

Given a <select> and an <input> element, both specified to be 200px wide:

<!doctype html>
<body>
<select style="width: 200px"></select><br/>
<input  style="width: 200px" type="text">
</body>
<html>

One ends up wider1,2,3, 4 than the other:

enter image description here

What is the reason for this?

If someone can give the reason, perhaps the solution would be obvious, and not a hack&pray.

Layout

The applied layout is perfectly reasonable:

enter image description here


Update 1: While i was writing this question Chrome updated itself from 17 to 19.

Update 2: Changing padding in the <input> from 1 to zero:

<!doctype html>
<body>
<select style="width: 200px"></select><br/>
<input style="width: 200px; padding: 0" type="text">
</body>
<html>

doesn't make the <input> 200px wide (i.e. doesn't fix it).

Update 3: Applying a CSS reset:

<!doctype html>
<head>
<style type="text/css">
   * {
       padding: 0;
       margin: 0;
   }
</style>
<body>
<select style="width: 200px"></select><br/>
<input style="width: 200px; padding: 0" type="text">
</body>
<html>

Does not solve the problem:

enter image description here

Also, i am less interested in a solution than an explanation.

Footnotes

  • 1,2,3 Chrome 1719, Firefox, Internet Explorer 9
  • 4 on Windows 7 64-bit

Bonus Reading

Your <input> isn't too wide; your <select> is too narrow!

The real issue is that the <select> element doesn't behave like most elements do. It uses a border-box model, where width is the width of the element after padding and borders are applied.

This runs counter to every other element when in "standards" mode; behaving as though it alone were in "quirks" mode.

The input element behaves like most elements do, using a content-box model, where the width is the width of the element before padding and borders are applied.

There are default padding and borders set by your browser, so it is larger than you might want and/or expect. I always use a "CSS reset" at the top of my stylesheets, like so:

* {
    padding: 0;
    margin: 0;
}

That will ensure there are no default padding or margins on any element.

The select element is a different case though, where is behaves more like an element with box-sizing: border-box enabled, where it takes into account borders and padding into its width specification.

If you add box-sizing: border-box to your input element, it will behave exactly as you expect/want.

EDIT: Bolded the part that may be relevant to you. An alternate solution is reducing the specified width of the input element by a few pixels, so that it matches the width of the select box.

Fiddle demonstrating both solutions: http://jsfiddle.net/n4yT2/2/

<i> tag for icons?

7 votes

I've looked into the source of facebook, they use the <i> tag to display icons.
Also, today I looked into twitter's bootstrap. It also uses <i> tag to display icons.

But,

From the HTML5 spec:

The i element represents a span of text in an alternate voice or mood, or otherwise offset from the normal prose, such as a taxonomic designation, a technical term, an idiomatic phrase from another language, a thought, a ship name, or some other prose whose typical typographic presentation is italicized.

Why are they using <i> tag to display icons ?

Is it not a bad practice ?

Or am I missing something here ?

Edit:

I am using span to display icons and it seems to be working for me till now.

Why are they using <i> tag to display icons ?

Because it is:

  • Short
  • i stands for icon (although not in HTML)

Is it not a bad practice ?

Awful practise. It is a triumph of performance over semantics.

What's the most efficient way of creating dynamic page body?

6 votes

I've took a look at the PHP script behind my father website which has been built by a hired programmer. Now, I'm not thinking that I'm better than him, but I think its technique might not be the best.

The website has dynamic page body, in the meaning that my dad can, via a specific admin page, modify the HTML content of most of the webpages in the website. Right now it's made via database: the pages are all stored in the database and every request deals with a query that fetches the page from the database and implement it.

Now, I think this way is very bad mostly because it requires (even if not that expensive if cached) an additional query to the database. Wouldn't it be more efficient to store the pages as HTML files and then just modify the file itself when required? In this way the editing of the file, I think, is faster, and the loading of the content of an html file per request is a lot easier and faster than perform a query.

Is it? Is there any other (more efficient) way to handling this situation?

There are several good reasons why a CMS should use a Database to store/fetch the dynamic content. Just as there are several reasons why you might prefer not to rely on a DB.

  • Pro Db:

    • Security: It's an obvious, and slightly ambivalent argument, but nonetheless. If you decide to store your content as separate files on your server, they'll need to be stored in a directory that doesn't allow public access. If not, users might be able to access the chunks of your site separatly, which comes across as unprofessional.
      People with ignoble intentions will have an easy time altering your site's content, too. Of course, there are many ways to prevent this, and increase overall security. Database systems, when left to their own devices, aren't exactly safe either, but provide an extra obstacle to hackers with minimal effort.
      note: The security argument stands, or falls with how well your script filters out injection, and how secure you set up your server.

    • Disk usage. When using separate files to compose each requested page, The server has to access its HD on each request. Again, caching solves this issue to some extend, but it's easier and (in general) better to cache DB query results (performance wise). Either on your Database server, in PHP, or, better still, both.

    • Logging. By this I mean: when you alter the content, a database driven CMS is a lot easier to manage. If you altered the content, and want to undo/rollback the changes, a DB is the easiest way to implement such a feature. Using HTML, you'll soon find yourself wading through tons of files called site_menu_block_YYYY-mm-dd.html.backup. Even if this is done by a script, it'll almost certainly be slower than using a DB.

    • Translation: as vlzvl pointed out, if you're using static pages, you'll either end up with each page N times, once for each language. When altering the stylesheets, you'll then have to alter N files, too. Which is resource expensive. Alternatively, your scripts will parse an HTML template file for each request, and an XML file with the actual contents. This way you loose the SEO benefit of the HTML files, and cause extra server load and slow down your site.

  • Pro HTML:

    • I can only give 1 solid pro argument here: it's a lot easier to get an SEO site this way. Just allow search engines to index the separate files. This does decrease the overall security of your CMS drastically .

That said, I think I'm right in saying that all major CMS's use both methods, depending on what type of data they're dealing with. HTML headers, for example, are often partially stored as separate files, just like JS files and style-sheets.