Showing posts with label cross browser. Show all posts
Showing posts with label cross browser. Show all posts

Monday, May 4, 2009

[CSS] Center DIV within DIV

This is one of those that'll give you nightmares.

You have a wrapper div and an inner DIV:
<div id="wrapper">
<div id="inner">
<!-- your rubbish here -->
</div>
</div>

Css styling below will do the trick - text-align: center will work on IE but won't work on other browsers (css compliant) which require margin: 0 auto:
/* for IE */
div#wrapper {
text-align: center;
}

div#inner {
margin: 0 auto; /* this centers the DIV */
width: 30%; /* whatever */
}

alternatively you could set left and right margin separately.

Friday, February 1, 2008

[Javascript] Change HTML "class" and "style" attributes

It seems trivial, and it is, but if you are going to write a cross browser script, you can find that sometimes (i.e. always) most used browsers, Firefox and Internet Explorer, work in different ways...damn it!
One of those troubles is the class attribute of a generic HTML; I found that in IE you cannot simply set a class attribute to your own HTML node, but you have to set a className node with the list of your CSS classes.
This is THE code:


/* find out which is the browser */
var isIE = (window.ActiveXObject)?true:false;
var isMozilla = (document.implementation.createDocument)?true:false;

/* the name of the attribute, depending on the browser */
var attributeClass = (isIE)?"className":"class";

/* set the attribute */
htmlNode.setAttribute(attributeClass,"classX dummyClass");


Moreover there is also another strange behavious as for the style attribute; if you want to set the whole CSS text of a node's style (and not a particular sub attribute), this is the syntax:

[UPDATE 01 feb. 2008 - 17:50]
Max and other users made me notice that "else if(isMozilla)" may exclude other
kind of browser, not allowing a wide "cross browsering". Thanx guys!



var styleString ="font-size:10px;";

if(isIE)
div.style.cssText=styleString ;
else //if(isMozilla)
div.setAttribute("style",styleString);


I assure you: writing cross browser script is a really butchery task! Try if you don't believe me!