Best css questions in December 2011

Unable to set marginTop style with script using IE8, but works in grown-up people browsers

16 votes

I'm attempting to animate the slide-out of a menu with script. To do this, I need to animate the marginTop property of an element and increment it from -30px to 0px.

However, in IE8, the animation simply does nothing. I've traced this down to the fact that setting marginTop in script seems to have no effect. In Chrome and Firefox, this works fine.

Here's an example that will work with Chrome/Firefox, but not IE:

http://jsfiddle.net/rm58T/2/

Is this an IE bug, and if so, are there any workarounds for this behavior? Thanks!

Update:

Here's some screen shots of the bug.

In Chrome, my Fiddle looks like this (You can see the "Name of new menu" text, since we changed the margin with script)

enter image description here

In IE8/Vista, it looks like this. I can confirm in Developer Tools that topMargin is actually 0px as expected, however the elements were not re-drawn:

enter image description here

Another Update:

This bug repros (at least for me) on IE8 running on Windows 7, and also IE8 running on Windows 2008 Server. It does NOT repro for me on IE7 running on WinXP. I do not have any IE9 machines to test it.

Yet Another Update:

I found one potential work-around. If I set p.newmenu to position: absolute; instead of position: relative; then it works. However, in my case I'm hosting this entire thing in a popup menu and need this control to push out the bottom of the modal dialog, so absolutely positioning it is not an option. However, perhaps this knowledge can help in finding a workable solution. An example of this work around can be found here.

Would You Believe Another Update?:

I did find a workaround for now. If I use top: -30px; instead of a negative top margin, then everything works. top behaves a bit differently than a margin, though, and makes the UI not look quite as nice. In particular, when you use top: -30px, then you'll have 30px of whitespace under your element since relative positioning doesn't affect other page flow.

I'd greatly like to figure out why I can't use a negative top margin on IE like I can with other browsers, so I'm still hoping someone can provide an answer that will provide all the benefits of a negative top margin but also work with IE8.

The trigger for this behaviour is how IE8 handles the fieldset element.

You can work around it by setting the display for fieldset to inline (or inline-block).

div.modal.addmenu fieldset {
   display: inline;   
}

Are repeated backgrounds in html more efficient if they are larger than 1px?

12 votes

If there is a one-dimensional background that is repeated on a certain dimension, is there any mentionable difference in performance if the image is e.g. 1px wide versus 10 or 20 pixels wide?

I assume you mean a two-dimensional background.

I can't imagine that there is any noticeable difference, on modern computers. However, because bandwidth is still at a premium, especially on mobile devices, I think you would be better off conserving bandwidth by repeating a 1px wide image instead of say 2 or 3 px wide.

UPDATE: We just ran a test, unscientifically, but certainly perceptually relevant, in which one page rendered a 10px green square over a 10,000,000px square div, and another page rendered a 1px green square over the same size div. All styles are set with CSS, both pages had no other content. The graphics were loaded locally. There was absolutely no perceptual difference in the rendering in either Safari 5 for Mac, or FireFox 8 for Mac. Still, it's possible that there could be performance issues on certain models of older (crappier) smart phones.

CSS "overflow" culls "background-color"

12 votes

I'm trying to style blocks of code for a website. The container div is set to overflow both vertically and horizontally. The problem is when it overflows horizontally, the zebra-striped background-color is culled. I tried it with a background image as well but it culls that too. Why is it doing that and how do I fix it?

Thanks.

Image: http://zero.robotrenegade.com/q3w/background-overflow.png

Webpage (scale your browser width down to see the problem): http://zero.robotrenegade.com/q3w/code.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="created" content="">
    <meta name="description" content="">
    <meta name="keywords" content="">
    <link rel="stylesheet" href="" type="text/css" media="all" title="Default styles" />
    <title></title>
    <!--[if IE]><script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            jQuery("pre code").html(function(index, html) {
                    return html.replace(/^(.*)$/mg, "<span class=\"line\">$1</span>")
            });
        });
    </script>
<style>
.codeblock {
    max-height: 25em;
    overflow: auto;
    margin: 1em;
    border: 1px solid #ccc;
    font-size: 1em;
    line-height: normal;
    border-radius: 8px;
    box-shadow: 0px 0px 4px rgba(0,0,0,0.25);
}
.codeblock h1, .codeblock p {
    font-size: 1em;
    margin: 0;
    padding: 0em 1em 0.5em 3.5em;
    line-height: 2em;
    background-color: #eee;
}
.codeblock pre {
    margin: 0;
    padding: 0;
    font-face: 'lucida console',monaco,courier,'courier new',monospace;
}
.codeblock pre code {
    counter-reset: line-numbering;
    margin: 0;
    padding: 0;
}
.codeblock pre code .line::before {
    content: counter(line-numbering);
    counter-increment: line-numbering;
    padding-right: 0.5em;
    width: 4.5em;
    text-align: right;
    color: #888;
    border-right: 1px dotted #888;
    display: inline-block;
    background-color: #eee;
}
.codeblock pre code .line {
    display: block;
    margin: 0 0 -1.2em 0;
    line-height: 1.5em;
}
.codeblock pre code .line:nth-child(odd) {
    background: #f2f5f9;
}
/*.codeblock pre code .line:hover {
    background: #4b95e5;
    color: #fff;
}*/
</style>

</head>
<body>

<div class="codeblock"><!--<h1>Hello, this is an optional header.</h1>-->
<pre><code>void idAF::Restore( idRestoreGame *savefile ) {
    savefile->ReadObject( reinterpret_cast<idClass *&>( self ) );
    savefile->ReadString( name );
    savefile->ReadBool( hasBindConstraints );
    savefile->ReadVec3( baseOrigin );
    savefile->ReadMat3( baseAxis );
    savefile->ReadInt( poseTime );
    savefile->ReadInt( restStartTime );
    savefile->ReadBool( isLoaded );
    savefile->ReadBool( isActive );

    animator = NULL;
    modifiedAnim = 0;

    if ( self ) {
        SetAnimator( self->GetAnimator() );
        Load( self, name );
        if ( hasBindConstraints ) {
            AddBindConstraints();
        }
    }

    savefile->ReadStaticObject( physicsObj );

    if ( self ) {
        if ( isActive ) {
            // clear all animations
            animator->ClearAllAnims( gameLocal.time, 0 );
            animator->ClearAllJoints();

            // switch to articulated figure physics
            self->RestorePhysics( &physicsObj );
            physicsObj.EnableClip();
        }
        UpdateAnimation();
    }
}</code></pre>
<!-- <p>This is an optional footer, goodbye!</p> -->
</div>

</body>
</html>

Try float:left on the .codeblock pre. Works in Firefox.

<pre> fits itself inside the .codeblock container like there was no more room. float makes your <pre> element wide just enough to fit its content.

UPDATE

.codeblock pre {
    float: left;
    min-width: 100%;}

Works in Firefox, Opera, IE9 and WebKit

As far as I understand, it elements inside a container with overflow:auto fit themselves inside the area that's visible by default. Those elements' width:100% is only as wide as the outer container. In this example inside of the inner container you have a code tag that doesn't break lines so the text goes outside the inner container and makes the outer container show scrolls. To avoid that, you need the inner container to fit its content hence float:left.

But, as you cleverly noticed (and I didn't), this way it won't expand if the outer container is wider than the code so to avoid that you need to put min-width:100% to make the inner container use at least all the visible space inside the outer container.

Calculate absolute dimensions of a div rotated in perspective with css3

12 votes

lets say we have a div with 500x500px size and we rotate it on the x axis via css 45 degrees considering a webkit-perspective value of 1600px.

How would you calculate the absolute dimensions of the displayed trapezium? (width, max-height, angles)

I did only figure out a formula that calculates the width but without considering the perspective, so the value differ some pixels (JavaScript):

var absoluteWidth = Math.cos(45 * (Math.PI / 180)) * 500);

EDIT: Here is the spec about the -webkit-perspective function:

perspective(<number>)

specifies a perspective projection matrix. This matrix maps a viewing cube onto a pyramid whose base is infinitely far away from the viewer and whose peak represents the viewer's position. The viewable area is the region bounded by the four edges of the viewport (the portion of the browser window used for rendering the webpage between the viewer's position and a point at a distance of infinity from the viewer). The depth, given as the parameter to the function, represents the distance of the z=0 plane from the viewer. Lower values give a more flattened pyramid and therefore a more pronounced perspective effect. The value is given in pixels, so a value of 1000 gives a moderate amount of foreshortening and a value of 200 gives an extreme amount. The matrix is computed by starting with an identity matrix and replacing the value at row 3, column 4 with the value -1/depth. The value for depth must be greater than zero, otherwise the function is invalid.

Regarding the "perspective projection matrix" this is what I found on Wikipedia: http://en.wikipedia.org/wiki/3D_projection#Perspective_projection

I get a headache with matrices, so I'm doing this with proportions.

If you see the div from above (hence seeing the rotation in the two dimensions it takes place in), you're seeing it as a segment on the xz plane, with coordinates (-250, 0) (250, 0), or in general (-w/2, 0) (w/2, 0) After a rotation on the y axis, the coordinates will become, similarly to what you stated

(-Math.cos(angle) * w/2, -Math.sin(angle) * w/2)
( Math.cos(angle) * w/2,  Math.sin(angle) * w/2)

, being the rotation counterclockwise, with the origin at the center of the div, and of angle radians.

Using the perspective means that these coordinates are not displayed just by discarding the z, but they are first projected according to their distance from the observer.

Now, the projection plane is the one where the unrotated things lay, with z = 0. I deduce this from the fact that when unrotated divs are projected, they remain the same size. If you take a point with distance p (the perspective value) from the z plane, so with xz coordinates (0, -p), and draw a line from this point to the vertices of the rotated segment, up to when it crosses the projection plan, the points you get are the new segment coordinates which yield the div final size.

With a proportion between the triangles (0, -p) (0, 0) (x, 0) and (0, -p) (0, sin*w/2) (cos*w/2, sin*w/2), you get that

p : x = (p + sin*w/2) : cos*w/2
x = (p * cos*w/2) / (p + sin*w/2)

which in general means that when you project the point (x, y, z) onto the plan you get

x * p / (p + z)
y * p / (p + z)
0

So your final div coordinates (on xz, relative to div's center) will be

(-Math.cos(angle) * w/2 * p / (p + -Math.sin(angle) * w/2), 0)
( Math.cos(angle) * w/2 * p / (p +  Math.sin(angle) * w/2), 0)

From which you can calculate its width but also its position - which is non trivial, since its nearest-to-the-viewer half will appear bigger than the other half.

Look at the following test for more details (it fails when you're too close to the objects, I'm not sure why, probably some variable overflows)

<!DOCTYPE html>
<html>
    <head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript">
    var WIDTH = 500;
    var P = 300;
    jQuery(function(){
        function test(width, angle, p) {
            $('body').
                append($('<div id="info" />')).
                append($('<div id="container" />').
                    css({
                        margin: '50px 0px',
                        border: '1px solid black',
                        width: width+'px',
                        '-webkit-perspective': p
                    }).
                    append($('<div id="real" />').addClass('the_div').css({ 'width': width+'px' }))).
                append($('<div id="fake" />').addClass('the_div'));

            setInterval(function() {
                angle += 1;

                $('#real').css({ '-webkit-transform': 'rotateY('+angle+'deg)' }).html(width);

                // initial coordinates
                var A = 0;
                var B = width;
                // translate the center (assuming -perspective-origin at 50%)
                A -= width/2;
                B -= width/2;
                // new coordinates
                A = calc(A, angle*Math.PI/180, p);
                B = calc(B, angle*Math.PI/180, p);
                // translate back
                A += width/2;
                B += width/2;
                if(B < A) { var tmp = A; A = B; B = tmp; } // swap
                var realwidth = B-A;
                $('#fake').html(width+'<br/>'+A+', '+B).css({
                    'width': realwidth+'px',
                    'margin-left': A+'px'
                });

                // shows debug information
                var debug = function(values) { return values.map(function(i){ return i+': '+eval(i); }).join('<br />'); }
                $('#info').html($('<div />').html(debug(['width', 'p', 'angle', 'A', 'B', 'realwidth'])));

            }, 40);
        }

        function calc(oldx, angle, p) {
            var x = Math.cos(angle) * oldx;
            var z = Math.sin(angle) * oldx;

            return x * p / (p+z);
        }

        test(WIDTH, 0, P);
    });
    </script>
    <style type="text/css">
        * { margin: 0px; padding: 0px; }
        body { padding: 40px 100px; }
        .the_div { height: 100px; border: 2px solid black; background-color: rgba(255, 192, 0, 0.5); }
    </style>
    </head>
    <body></body>
</html>

Note that if you're not giving a perspective value, the result will be equal as having an infinite value for it.

How to target a braille / screen-reader via CSS

11 votes

I use a webfont to display some icons on a website. This is fantastic because they scale, and i can print them if i want to... But the problem is that blind people see them as normal letters or characters. The following example returns me a nice Icon + text.

<span>i</span> Info
<span>t</span> Contact
etc...

A blind person will just read: iInfo, tContact etc...

Is it possible somehow to target only braille- & screen-readers with CSS?

I found this on the w3 website, but I'm not sure if the work in real live: http://www.w3.org/TR/CSS2/media.html#media-types

Does anyone have any experience with this?

------update-----

:before & :after -> Some screen-readers such as VoiceOver for MacOS do read the "content" part out loud. I have tested this by my self.

@media braille, speech -> Seams not to have a influence on VoiceOver. It reads whats visible on the screen (tested with safari & chrome)

speak: none; -> has no influence at all on VoiceOver or NVDA ( https://twitter.com/#!/jcsteh/status/143848614979055616 )

I think there is no "ultimate solution" to this. But you can use the abbr-tag to describe the use of your font-char, therefore most screen-readers will read-out the title-param of abbr and the user gets the meaning of the 'icon-character'.

I'm not 100% sure, but as it seams NVDA, JAWS and VoiceOver for iOS this works — on Mac OS X (unfortunately) not

Example:

<abbr title="Attachment Icon">A</abbr>

Best way to do curved shadows

10 votes

For something like this:

box

What would be the most effective way to do this? Best to do an image, or is there a way to achieve this with CSS without a bunch of hacks/extra markup that I dont know about?

Also the shadow only has to work in IE9, FF, and Chrome

You would do so using pseudo-elements and the box-shadow property. I have done up an example for you here: http://jsfiddle.net/sl1dr/NWnXw/

This works in IE9 and up.

/* Shadow */

.shadow {
    box-shadow: 0 1px 5px hsla(0,0%,0%,.25),
                inset 0 0 50px hsla(0,0%,0%,.05);
    position: relative;
}
.shadow:after,
.shadow:before {
    bottom: 7px;
    box-shadow: 0 10px 15px hsla(0,0%,0%,.25);
    content: '';
    height: 50%;
    left: 7px;
    max-width: 300px;
    position: absolute;
    right: 7px;
    z-index: -1;
    -webkit-transform: skew(-15deg) rotate(-8deg);
       -moz-transform: skew(-15deg) rotate(-6deg);
        -ms-transform: skew(-15deg) rotate(-6deg);
         -o-transform: skew(-15deg) rotate(-6deg);
            transform: skew(-15deg) rotate(-6deg);
}
.shadow:after {
    -webkit-transform: skew(15deg) rotate(8deg);
       -moz-transform: skew(15deg) rotate(6deg);
        -ms-transform: skew(15deg) rotate(6deg);
         -o-transform: skew(15deg) rotate(6deg);
            transform: skew(15deg) rotate(6deg);
}

Reasons for not using CSS to visually rearrange order of HTML elements

10 votes

We're having a bit of a discussion in the office at the moment about using CSS to visually re-order elements on the page.

On a very basic level, a member of our team wants to structure the HTML like this (this request is based solely on a design perspective)

<div class="secondary-content">
    <h2>Secondary content heading</h2>
    <p>This is the secondary content</p>
</div>
<div class="main-content">
    <h1>Main heading</h1>
    <p>This is the main content</p>
</div>

and then use CSS to visually place the main-content div before the secondary-content one.

Now, I'm not asking for help on how we would technically achieve this, but more I'm looking for evidence to back up the argument that we shouldn't do it at all.

As a front-end dev, my intial concerns are around accessibility

  1. Screen readers/assistive technologies will hit the secondary-content first. To me, that's akin to opening a book, starting at chapter 4 and then going back and reading chapters 1, 2, 3, 5, 6 etc
  2. The heading structure of the page will be disjointed (H2 before H1 etc)
  3. If there is any content in secondary-content which requires info from main-content in order to be understood, it will be confusing for users with CSS off/assistive technologies etc

However, the real hot button for people in the business is Google/SEO. Therefore, does anyone know any good arguments/articles as to why writing the HTML in an ill-structured way would negatively impact our SEO?

[Would] writing the HTML in an ill-structured way would negatively impact our SEO?

Almost definitely. While the precise nature of search ranking algorithms is a jealously guarded industry secret, and each company is different, everyone looks unfavorably on differences between content presented to search engines versus that presented to users.

Here's what Google's Webmaster Guidelines say:

  • Create a useful, information-rich site, and write pages that clearly and accurately describe your content. [Pages whose content obfuscates the actual visual ordering are not clearly and accurately describing their content.]

  • Make a site with a clear hierarchy and text links. [Putting a <h2> before a <h1> violates a hierarchy.]

  • Use a text browser such as Lynx to examine your site, because most search engine spiders see your site much as Lynx would. [Someone using a text browser would certainly be confused by bizarre content reordering schemes.]

So, in short, you're meddling with the "clear hierarchy" that search engines are trying to index. That's clearly not desirable.

To answer your more general question:

I'm looking for evidence to back up the argument that we shouldn't do it at all.

Fundamentally, HTML documents are just that: documents, meant for conveying semantic information through their structure.

Attempting to subvert this natural ordering isn't strictly verboten, but it often suggests that you didn't write the markup correctly, and it always leads to unexpected flows. For example,

  • In a book, do you expect chapter 7 to come before chapter 6?
  • In a newspaper article, do you expect the body to come before the headline?
  • In a movie, do you expect the closing credits to come before the title card?

You can see why, structurally, it would be ill-advised to reorder elements in this way. A document has a natural shape; distorting it makes it harder to understand.

There may be compelling aesthetic or artistic reasons to change the form of semantic vehicles like documents (e.g., a movie like Memento which exploits this for deliberate effect), but these are usually well thought-out, and not done trivially.

And you'd be hard-pressed to make an equivalence between a movie, which is designed to entertain, and an HTML document, which is designed to inform.

Style text inside textarea like Facebook does

10 votes

I try to achieve something like the Facebook does when you type @<NAME_OF_A_FRIEND> in a reply. After you choose a friend, the name of that friend is highlighted with a blueish background, so you know it's a separate entity in that text.

I've "inspect element"-ed that textarea and there is no div placed on top of the textarea.

Can anyone give me a clue about how that is done ?

enter image description here

See this example here. I used only CSS and HTML... The JS is very more complex for now. I don't know exactly what you expect.

HTML:

<div id="textback">
    <div id="backmodel"></div>
</div>
<textarea id="textarea">Hey Nicolae, it is just a test!</textarea>

CSS:

#textarea {
    background: transparent;
    border: 1px #ddd solid;
    position: absolute;
    top: 5px;
    left: 5px;
    width: 400px;
    height: 120px;
    font: 9pt Consolas;
}

#backmodel {
    position: absolute;
    top: 7px;
    left: 32px;
    background-color: #D8DFEA;
    width: 53px;
    height: 9pt;
}

Including CSS with `<link>` or `@import` - which is better?

10 votes

i have a website and i have multiple css style sheet for print, tv, screen, handheld etc...

i want to know which one of these method is better to use (performance, usability, etc...)

<link href="all.css" media="all" type="text/css" />
<link href="handheld.css" media="handheld" type="text/css" />
<link href="tv_print.css" media="tv, print" type="text/css" />

or

<style type="text/css">
    @import url("all.css") all;
    @import url("handheld.css") handheld;
    @import url("tv_print.css") tv, print;
</style>

thank you

The first method (link) is the best.

The main reason is that there is a bug in IE 6,7 and 8 (not sure about 9 or higher) means that when you use @import in conjunction with link the files are loading in series rather than in parallel. This can slow things down a lot when using more than one style sheet.

Just using @import downloads in series, but the order isn't guaranteed, meaning that if there is a reset for instance, that may or may not be applied first.

This article has a good summary: http://www.stevesouders.com/blog/2009/04/09/dont-use-import/

Is it possible to determine which elements have margin auto?

9 votes

We have a situation in our project when resizing a container. It seems to be impossible to keep the "auto" value for our elements margin.

For example when trying to get the margin value with javascript or jquery, the value always returns 0. We really need to keep "auto" when resizing, so is there a way to determine which elements have margin: auto;

Even if it's possible using raw javascript?

----------------- Possible solution but needs Extending -----------------

I have found this useful. Which in fact solves part of the problem!

Retrieve element margin if it's 'auto' (Answer 3)

if($(this).position().left*2 == ($(this).parent().innerWidth() - $(this).outerWidth())) {
  console.info($(this).attr('id'));
}

However this matches far to many elements, so need to somehow be more specific. hopefully someone knows how to improve this code?

Thanks to Vigrond previous answer above. I was able to research further into the CSS Rule Object.

Finally I have come up with my own solution to return the actual CSS rules direct from the style-sheet! This not only solves my problem with margin auto, it also allows me to return all other css values which are not returned by the jquery CSS object.

Although the code could be optimized further. I am very happy with the result, also I added a white list as in my case it is not necessary to loop through all style-sheets.

Here is the code I ended up with!

var cssObj  = {};
function getStyle(element) {    
  var extractStyles = function(cssText) {
    var css = {};
    regEx   = /\.*\{[^\}](.*)}/im;
    styles  = cssText.match(regEx)[1].split(';');
    $.each(styles, function(k, style) {
      $key = style.split(':')[0].trim();
      $val = style.split(':')[1];
      if($key != '')
        css[$key] = $val.trim();
    });
    return css;
  };
  var sheets    = document.styleSheets;
  var whiteList = [
    cssPath+'product.css',
    cssPath+'style.css'
  ];
  $.each(sheets, function(key, sheet) {
    if($.inArray(sheet.href, whiteList) >=0) {
      $rules = sheet.rules || sheet.cssRules;
      $.each($rules, function(key, rule) {
        if(element.is(rule.selectorText)) {
          if(typeof(rule.cssText) != 'undefined' && rule.cssText) {
            cssObj[rule.selectorText] = extractStyles(rule.cssText);
          } else {
            cssObj[rule.selectorText] = (typeof(rule.cssText) != 'undefined' ? extractStyles(rule.style.cssText) : '');
          }
        }
     });
    }
 });
}

hide line beginning and end text separators

9 votes

two solutions below: one with pure css, the second with jQuery, allowing any kind of symbol/image to be a separator

pre: Fairly hard to formulate and find such questions/solutions so I am sorry if duplicating.

I have a multi-line, justified block with random(not entirely) text hyperlink elements (tags/categories/etc) without fixed width separated by "|" symbol and spaces around. Looks pretty much like a tag cloud but with a fixed font-weight, size and other formatting, can contain more than one word in a hyperlink element. The problem rises when a separator is placed just before the end of the line or at the beginning of the line, actually, it happens always one way or another as I set nowrap to link elements, so this looks really ugly. Seeking for a solution to remove separators in the beginning and end of the lines.

For better understanding I will try to draw an example here.

C++ | PHP | CSS | ASP |
JavaScript | jQuery
| HTML 5 | StackOverflow

Something like that, of course, with justification and much more lines in a row. And another drawing of what I want to achieve.

C++ | PHP | CSS | ASP
JavaScript | jQuery
HTML 5 | StackOverflow

So fixed number of elements in a line is not an option, fixed width is also not an option.

The only solution I came up with is to set font to monospace and to count symbols and print pragmatically line-by-line with server-side scripting, the downside, of course, is the monospace fonts. Seeking for a better solution like pure html/css (would be perfect), JavaScript/jQuery formatting after output.

Thank you in advance!

EDIT: answering to a comment below, markup can be anything you wish, basically something like:

<div><a href="#">tag 1</a> | <a href="#">tag 2</a> | <a href="#">tag 3</a></div>

Here's an idea: http://jsfiddle.net/WyeSz/
(note that the jsfiddle demo uses a CSS reset, you may need a little more CSS than this to reset list styles, etc.)

Basically, you set border-left on the list items, then position the entire list -1px to the left within a container that has overflow:hidden, which cuts off the left borders.

<div>
    <ul>
        <li>C++</li>
        <li>PHP</li>
        <li>CSS</li>
        <li>ASP</li>
        <li>JavaScript</li>
        <li>jQuery</li>
        <li>HTML 5</li>
        <li>StackOverflow</li>
    </ul>
</div>
ul {
    width:200px;  
    margin-left:-1px;/* hide the left borders */
}
li {
    float:left;   
    padding:2px 10px;
    border-left:1px solid #000;
}
div {
   overflow:hidden;/* hide the left borders */  
}

difficult HTML, JavaScript, CSS grid page

8 votes

FYI, This is a simplified/generic example of what I'm working on. I'm just looking for the HTML, JavaScript, and/or CSS that can make this work. I'd prefer that this can be done without any javascript library. Also, the page will be built based on data loaded from a database. This only needs to work in newer IE/Firefox browsers.

I need to create a web page that has a grid of fixed size "cells" on it, each cell will be 150 pixels by 150 pixels. Here is sample 6x3 grid, but my grids will vary in size (4x10 or 3x5, etc. as per the database data):

-------------------------------------
|     |     |     |     |     |     |
|     |     |     |     |     |     |
|     |     |     |     |     |     |
-------------------------------------
|     |     |     |     |     |     |
|     |     |     |     |     |     |       6x3 grid of "cells"
|     |     |     |     |     |     |
-------------------------------------
|     |     |     |     |     |     |
|     |     |     |     |     |     |
|     |     |     |     |     |     |
-------------------------------------

each of these cells will need the following:

1) contain a "main" image that is 150 pixels by 150 pixels. This image will need to be changed in the browser, hopefully using CSS sprites if possible. I'd like to stick all of these images into a single file and crop down to what is needed in each cell.

2) When the mouse is over a "Cell", an overlay of click-able images will display. In the sample below I use letters, but the images will not be letters, more like icons. These clicks need to be able to run a different per image javascript function (so a click on the "A" image will run function A, while a click on "F" will run function F, etc). Images will be dependent on database info, so for different cells, some will be included and other not. Their position within the cell will always be fixed and controlled. Here is what a single cell might look with the images (letters) over top:

---------
|A  B  C|
|D  E  F|     a single cell where all overlay images appear
|G  H  I|
---------

---------
|A     C|
|   E   |     a single cell where only some overlay images appear
|G      |
---------

3) free text wrapping and centered within the cell. It would be best if this free text was above the main image #1 and below the click-able images #2, but if it was on top of everything than that would be OK too. There will be a reasonable length limit on this text, so scrolling beyond the 150px x 150px should not be an issue, but it will need to wrap.

For the record, this is not homework! and HTML/javascript/CSS is certainly not my strength. I have been working at this for a while and have seen/worked with many examples of how to do various components of this. I've yet to find anything that can work when everything id put together.

Personally I think tables are the devil, so here is something more like what I would do that uses floated divs:

http://jsfiddle.net/gbcd6/11/

You could easily swap out the text content for images, or add background images through CSS, as well as call separate JS functions based on the one-nine class each "control" div has.

EDIT:

Here is the most current version of the solution, which does include an actual table rather than using display: table-cell, as well as additional example markup for images and wrapping, and a basic Javascript example. This was done to fix an issue with older browser support, and to meet KM's requirements. Though the overall structure is still pretty much the same as the original fiddle.

Dynamically adjusting two outside columns to the variable width of the center column

7 votes

I would consider myself to be an intermediate/advanced CSS/HTML coder but I'm stumped on how to do the following scenario.. I'm starting to think it is impossible but I really want to believe it is..

Let's say the wrapper width is 1000px.

Within it is three columns. The two outside columns are the same width, this width is decided by the center column. The center column is the only one with content, just one line of text with 30px of padding on either side. So if the line of content is 100px with padding, than the other two columns would be (1000-100)/2 each..

Is there a dynamic way to have the two outside columns adjust to the varying width of the center column that is defined by its varying contents, one line of text?

Graphic of what I am trying to accomplish:

http://i.stack.imgur.com/cMuBP.png

Good 'ole tables to the rescue:

http://jsfiddle.net/hgwdT/

Actually I think tables are the devil, but this works as you described. And so here it is using display: table-cell on the child divs, so it is functionally the same using nicer markup:

http://jsfiddle.net/XXXdB/

The center element can indeed have a dynamic width; to prevent the content from being squished, I simply added a white-space: nowrap to the p containing the text.

I also confirmed that this solution works in IE8 and FF, in addition to Chrome.

Facebook Like button causing horizontal scrolling on mobile device

7 votes

I have a Facebook Like button implementation which is rendering fine in all browsers desktop and mobile. But the issues lies on low-res devices with resolution of 240x320. the Like button is causing the device to zoom into the page thus rendering horizontal scrolling.

The buttons is rendering fine on devices with width >= 320px like the iPhone etc., but older android devices with width less than that are facing issues.

The way I see it. The page loads fine, then makes a server call to Facebook and then returns with some parameter that breaks it all up. It is generating an <iframe>. I am trying to put width and overflow CSS parameters but none seem to work. I am initializing the Like button like this:

<div id="fb-root">
<!--Facebook begins-->       
        <div class="fb-like" data-href="<%=RedirectURL%>" data-send="false" data-layout="button_count" width="80" data-show-faces="false"></div>
        <!-- ends -->
</div> 

<script>
        window.fbAsyncInit = function () {
            FB.init({ appId: '328982000461228', status: true, cookie: true,
                xfbml: true
            });
            FB.Event.subscribe('edge.create', function (response) {
                ntptEventTag('ev=Social&Action=Method Shared');
            });
        };
        </script>
    <script type="text/javascript">

None of the above solutions helped. Finally got the answer. Although it is not the best solution, but it gets the job done.

I applied this to the parent container of the fb like button:

.socialIcons { display: inline-block; width: 200%; /* for low res androids */ overflow: hidden; margin: 5px 0 5px 10px; }

Website Join Form - Location Geo Co-Ordinates

4 votes

I have a website with a join form that asks you for your country and then city. When you type your city it sends AJAX calls back to a MySQL DB I have and this returns 10 possible results in a div under the input that you can select from or type further for a more refined return.

enter image description here

This works fine for one country (I purchased this DB) but I need to expand it for the entire world. I can purchase a DB for the world (country, city, suburb, postcode, geo co-ordinates) but its not cheap so I wanted to ask.

  1. Is there a way to do the same thing using Google Maps, Yahoo or Bing? Can I have users enter a country city location and have the GEO CO-Ords returned? Is it possible to do this with the AJAX keyup event returning possibilities?

  2. How to other people/sites go about this.

Note: I should also explain why I need this. The site is for online dating and I need to do radius searches. Eg: search for other members within 10KM or 20KM from where I am so I need GEO CO-Ords for each member.

Any advice would be greatly appreciated.

I have used Geonames in my previous geo-based project, what I did was:

  1. Downloaded the free database from the site.
  2. Imported the country, city, admin area database.
  3. Created my own Ajax service and various functions based on the imported database.

To make a query quick enough for your auto-complete input form, you might want to reduce the data size of the cities table by eliminating less populated cities by using "cities1000.zip" (which stands for "all cities with a population > 1000). I used this solution and the search speed was at least 1000x times faster.

And a quick answer for your "radius searches", you can use these Reverse Geocoding Webservices from Geonames as well.

Why are these XML tags creating an error in my PHP?

4 votes

I am trying to use XML in a PHP document. I am getting an error for the <?xml and the ?> tags. I assume PHP is trying to read the XML tags as PHP tags. Does anyone know what bug is?

<body>
     <?xml-stylesheet type="text/css" href="stylebox.css" ?> 
     <svg xmlns="http://www.w3.org/2000/svg" version="1.1">
         <rect id="p1" x="100" y="100" width="100" height="100" />
         <rect id="p2" x="200" y="100" width="100" height="100" />
     </svg>
</body>

This is short php open tags creating problem. Change settings in you php.ini file

Put :

short_open_tag = Off

Otherwise assign this value in a variable in place of <?xml-stylesheet type="text/css" href="stylebox.css" ?> :

$XMLstr='<?xml-stylesheet type="text/css" href="stylebox.css" ?>';

echo $XMLstr;