Posts Tagged ‘css’

Telerik RadComboBox Visual Artifact in IE9 Compatibility Mode

We have a web application that we support for IE 7, 8, and 9, both in and out of compatibility mode, and, despite the quirks between the three versions, we fortunately don’t run into too many browser-specific issues. I did have to recently address an odd visual artifact, though, that appeared on our RadComboBoxes after we upgraded our Telerik .dll’s to the latest version. It wasn’t present in IE8, but did pop up in IE7 and IE9 Compatibility Mode: RadComboBox - IE9 - Compatibility Mode - Artifact That tiny 4×1 gray spot was maddening; we were just using the default styling for the Telerik controls and the only things that changed were the Telerik .dll’s, themselves, so it couldn’t be a problem with our application, right? Wrong! The Telerik controls are built from several basic HTML elements and the one causing us grief was the “a” tag used for the dropdownlist arrow: RadComboBox-HTML.png Turns out that we had defined a CSS class for that element and it was the “word-wrap” that was breaking everything:

A
{
    WORD-WRAP: break-word;
    COLOR: #2d66b3;
    TEXT-DECORATION: underline
}

Once we had that pinned down, it was just a matter of setting something up to override that for the RadComboBox:

.RadComboBox TD.rcbArrowCell A
{
    word-wrap: normal;
}

Just goes to show that you never know what quirks might appear with even the most innocuous of updates.

Tags: , , ,


CSS Menus and Unordered Lists

 

Why use CSS Menus?

The short answer … because they are awesome. If you do much web programming, especially if you are more of a programmer than a designer, you have probably had the opportunity to sit in front of the computer and come up with some type of menu schema that will look nice and work properly across all browsers. This can often be a very frustrating experience, but help has arrived … I give you CSS and an unordered list. This concept is certainly not new, but it is powerful and worth reviewing.

The truth is that you can find many different controls that will produce a menu for you. Among them are:

There is even the Microsoft provided menu control, which you can find here:

Microsoft Menu Control

Now, it is not my intention to bash any of these controls. I actually think that they are all very beautiful and quite impressive. Here at TLS, I have used several Telerik controls with excellent results. Nevertheless, building a great looking menu is not anywhere near as difficult as it used to be and it can now be done using nothing but an unordered list and some CSS tags. If you want to spruce your menu up a little bit more, you can also include an image or two but that is not necessary.

Making a menu like this has several advantages.

  • Cross Browser Compatibility – Any browser that supports CSS (which by now should be all of them) will render your menu correctly. If you feel compelled to do so, you could add in some CSS for older IE versions, but I say …. If you are still using IE5 or IE6, that is your problem, not mine.
  • Code Simplicity – By this I mean that the amount of code on the page necessary to actually render the menu using an unordered list is much smaller than any other kind of menu you could use.
  • Graceful Failability – In other words, if for whatever reason, your styles are not working or javascript is turned off or the user has some ancient browser that doesn’t support modern CSS or Javascript, then the menu will still render as a normal Unordered List, which works perfectly fine as a menu, even if it is not the flashy affair that you envisioned.
  • Mobile Device Scalability – Lets face it, gone are the days in which you could plan on a user having either an IE or a Mozilla browser. Now a user could be on any number of browsers as well as an iPhone, an iPad, an Android Phone (all 2,394 models each with a different resolution), a Kindle Fire, a Windows Phone (I hope) and even an old non-smart phone with internet access. A menu done this way is far more likely to work correctly and look good on the lot of them.
 

Creating a CSS Menu

So … lets see some examples. First of all, we need to create our menu. This is very simple, just create an unordered list of some values. Mine will look like this:

<ul>
    <li><a href="#">Michael Westen</a></li>
    <li><a href="#">Sam Axe</a></li>
    <li><a href="#">Fiona Glenanne</a></li>
    <li><a href="#">Madeline Westen</a></li>
    <li><a href="#">Jesse Porter</a></li>
</ul>

When actually rendered on a page, it will look like so (Bullets and all):

 

As I mentioned, while not pretty, this is certainly serviceable as a menu if the CSS wasn’t working for some reason. By contrast, go look at a website using a complex menu control and then disable javascript and css … the result will be ugly and generally not even recognizable as a menu. But to make ours into a pretty menu, we are first going to add some styles to our unordered list which can then be used to make the list look more like a classic webpage menu. The first thing that we have to do, is set up a style identifying this list as a menu so that it will behave differently than other unordered lists that we might have on our webpage. The first thing that we need to do is to encase the unordered list in a containing tag. I will use a “div” tag. This gives us a couple of advantages, such as making sure that it extends to 100% of the element that it is inside of and allowing us to set a background color for the menu as a whole. Then we will give the container a class name … I’ll call it CssMenu. Like so:

<ul id="Menu">
    <li><a href="#">Michael Westen</a></li>
    <li><a href="#">Sam Axe</a></li>
    <li><a href="#">Fiona Glenanne</a></li>
    <li><a href="#">Madeline Westen</a></li>
    <li><a href="#">Jesse Porter</a></li>
</ul>
 

Now, this will not do anything to make the menu display different because we haven’t defined a CSS Style for “CssMenu” yet. So the next step is to style the unordered list so that it is starting to appear the way we want it to appear. To begin with, we will set the margins and paddings to 0 and then also set the height. Most importantly, we will set the “list-style-type” attribute to “None” so that it does not actually look like a list. The style tag would look like this:

        #Menu
        {
            margin: 0px;
            padding: 0px;
            list-style-type: none;
            height: 25px;
        }
 

Doing that gives us the following result:

If you wanted a vertical menu, then what we have right here would work pretty well, but I want our menu to be horizontal, so I will add additional style tags to make the “li” items in the list line up next to one another as opposed to on top of one another. The style for that looks like this:

        #Menu li
        {
            float: left;
        }
 

At this point, our list items are lining up one after the other like this:

 

There is nothing earth shattering here, I know, but I’m trying to go step by step. Believe it or not, we are almost there. From here, we just need to style the links on each list items so that they look pretty. Anyone with CSS experience should be able to do this with relative ease. In my case, I added things like a border, a background color, font family, font size etc. By adding padding also, you can add some space between the end of the word and the end of the link. By adding a right margin, you can separate each link into its own space. Also, by setting the display to “block” you can set the height or the width and have that value stick. Since block elements take up 100% of whatever they are inside of unless told otherwise, this means that the link will take the entire width of the list item. By adding in the following styles:

        #Menu a
        {
            border: solid 1px #000066;
            border-bottom: solid 1px #99000;
            background-color: #EDECD1;
            padding-right: 20px;
            padding-left: 20px;
            margin-right: 4px;
            display: block;
            line-height: 25px;
            font-family: Verdana, Tahoma, Arial;
            font-size: 10pt;
            color: #333333;
            text-decoration: none;
        }
 

My unordered list now looks like this:

 

To add some pizzazz, now, I am also going to add a style to the link so that it changes color when the mouse pointer hovers over it. Once again, this is very simple css code …. like this:

        #Menu a:hover
        {
            background-color: #990000;
            color: #ffffff;   
            border-bottom: solid 1px #990000;
        }
 

Now when the mouse hovers over a menu item, it will change color.

 

At this point, it is quite easy to put a content div tag right below the menu and make the colors match so that the menu appears to work in conjunction with the are below it … like this:

 

Conclusion

From here, the possibilities are endless. You could do all kinds of things using a few more simple css concepts like adding images or wrapping the menu in other tags. I’m not going to go into that, but I will say that in just a few lines of code here (with no images or javascript) we have made a nice little menu. If you are interested in more ideas as to how you could use these concepts, click here … but prepare to have your mind blown when you see all that can be accomplished just using CSS.

Tags: , ,


Mutually Exclusive CheckBoxListCheckBoxList Mutuamente Excluyentes

ASP.NET provides two useful server controls that allows one to choose from several available options, the CheckBoxList and RadioButtonList controls. The functionality of these controls is very similar and the primary difference is that the CheckBoxList allows multiple items to be selected where as the RadioButtonList only allows one item to be selected. There is one quirk with the RadioButtonList, once a selection is made it cannot be removed, by default. Recently a client asked if we could implement a CheckBoxList that included the the functionality of a RadioButtonList where a given option could be removed, but the options were mutually exclusive. Thanks to jQuery, implementing the desired behavior was relatively easy.

Below is an example of the HTML markup along with the jQuery code that was used.

<form id="frmOptions" runat="server">
<div class="divOptions">
    <asp:CheckBoxList ID="cblOptions" runat="server" class="cbl">
        <asp:ListItem Text="Option 1" Value="1" />
        <asp:ListItem Text="Option 2" Value="2" />
        <asp:ListItem Text="Option 3" Value="3" />
        <asp:ListItem Text="Option 4" Value="4" />
        <asp:ListItem Text="Option 5" Value="5" />
    </asp:CheckBoxList>
    <br />
    <br />
    <h3 class="subHeader" style="margin: 0">Note:</h3>
    <ul id="notes" style="margin-top: 0">
        <li>Clicking on any of the individual checkboxes, clears the previous selection.</li>
        <li>Clicking the same checkbox toggles the selection (default behavior).</li>
    </ul>
</div>
</form>
$(function () {
    // get all the checkboxes
    var $tblChkBox = $("table.cbl input:checkbox");

    // add a click handler to each checkbox
    $tblChkBox.click(function () {
        // get the id of the selected checkbox
        var selectedId = this.id;

        // uncheck all checkboxes except the selected one
        $tblChkBox.each(function () {
            if(this.id != selectedId) this.checked = false;
        });
    });
});

In this example, once the page loads and the document is ready, all the input elements of the checkbox type within the table are located based on the css class “cbl”. Note the checkboxlist renders as an HTML table. A click event handler is then added to each checkbox to clear the other checkboxes and the default toggle behavior of the selected checkbox is maintained.

If you’re new to jQuery, the Getting Started with jQuery tutorials are a good place to start. Rick Strahl also has a great introduction to jQuery article and the Learning jQuery site is excellent with categories/filters based on your skill level.ASP.NET proporciona dos controles de servidor útil que permite elegir entre varias opciones disponibles, los controles CheckBoxList y RadioButtonList. La funcionalidad de estos controles es muy similar y la diferencia principal es que el CheckBoxList permite que varios elementos para ser seleccionados en el RadioButtonList sólo permite un elemento a seleccionar. No es un capricho con el RadioButtonList, una vez que se realiza una selección que no se puede quitar, de forma predeterminada. Recientemente un cliente me preguntó si podíamos implementar un CheckBoxList que incluyó la funcionalidad de la de un RadioButtonList en que una opción dada eliminado, pero las opciones se excluyen mutuamente. Gracias a jQuery, la aplicación de la conducta deseada es relativamente fácil.

A continuación se muestra un ejemplo del código HTML, junto con el código jQuery que se utilizó.

<form id="frmOpcions" runat="server">
<div class="divOpcion">
    <asp:CheckBoxList ID="cblOpcions" runat="server" class="cbl">
        <asp:ListItem Text="Opción 1" Value="1" />
        <asp:ListItem Text="Opción 2" Value="2" />
        <asp:ListItem Text="Opción 3" Value="3" />
        <asp:ListItem Text="Opción 4" Value="4" />
        <asp:ListItem Text="Opción 5" Value="5" />
    </asp:CheckBoxList>
    <br />
    <br />
    <h3 class="subHeader" style="margin: 0">Nota:</h3>
    <ul id="notas" style="margin-top: 0">
        <li>Al hacer clic en cualquiera de las cajas de opciones individuales, se borra la selección anterior.</li>
        <li>Al hacer clic en la casilla de verificación activa o desactiva la misma selección (por defecto).</li>
    </ul>
</div>
</form>
$(function () {
    // conseguir todas las casillas de verificación
    var $tblChkBox = $("table.cbl input:checkbox");

    // agregar un controlador haga clic en cada casilla
    $tblChkBox.click(function () {
        // obtener el id de la casilla seleccionada
        var selectedId = this.id;

        // desactive todas las casillas excepto la seleccionada
        $tblChkBox.each(function () {
            if(this.id != selectedId) this.checked = false;
        });
    });
});

En este ejemplo, una vez que se carga la página y el documento está listo, todos los elementos de entrada del tipo de casilla en la tabla se encuentra basada en la clase CSS “CBL”. Tenga en cuenta la hace CheckBoxList como una tabla HTML. Un controlador de eventos haga clic entonces se agrega a cada casilla para desactivar las casillas de verificación de otros y el comportamiento por defecto de cambiar la casilla de verificación seleccionada se mantiene.

Tags: , , , ,


IE7 vs IE8: CSS, Positions, and Nested DivsIE7 vs IE8: CSS, Positions, and Divs Anidados

While it is widely known that there are many differences in how IE7 and IE8 handle CSS, I’m still occasionally thrown off by the quirks. Long story short, there was simultaneous development happening on one of our projects where coordination between developers was impossible, but overlapping development was not permitted. Fortunately, a feature of this project is that it’s capable of rendering content based on metadata, meaning I could define elements without touching the existing code, but was limited to inline CSS to position and style them.

With how certain container elements were rendered by default, it was necessary to use the Position attribute to place the new element where it needed to go. However, when experimenting with styles, I found that using a relatively-placed div container with an absolutely-placed child element displayed different behavior between IE7 and IE8:

IE7:

 

IE8:

 

I wanted to move the container div 170 pixels to the left, so I gave it a relative position and left attribute of “-170″, which allowed the element to display correctly in both browsers. However, out of curiousity, I gave the child element an absolute position and set both top and left attributes to “inherit”. The element was now placed too far to the left in IE8, so I adjusted the parent element’s left attribute to “-85″, which resulted in the layout that can be seen in the screenshots above.

Granted, I had to go out of my way to break the CSS, but I wasn’t expecting the browsers to interpret the “inherit” differently. Of course, removing the absolute positioning on the child or setting its left attribute to zero pixels fixes the issue, but it helped illustrate to me just how important it is to test your styles in as many browsers as is reasonably possible. Sure, you can’t code for every situation, but you can try!

There’s a great article that covers the differences between IE6, IE7, and IE8 by Louis Lazaris, CSS Differences in Internet Explorer 6, 7 and 8, and there’s always www.quirksmode.org, which documents the differences between IE and other browsers.Es bien sabido que existen muchas diferencias en la forma en que IE7 e IE8 manejan CSS, aun así en ocasiones soy un poco caprichoso. Para no hacer la historia muy larga, en uno de nuestros proyectos hay desarrollo simultáneo y la coordinación entre los desarrolladores era imposible, y el hecho de sentarse al lado del otro desarrollador para programar en conjunto no se nos permitió. Afortunadamente, una característica de este proyecto es que es capaz de representar el contenido basado en los metadatos, lo que significa que podría definir los elementos sin tocar el código existente, pero se limitó a CSS “inline” para establecer la posición y el estilo de los metadatos.

Para qué ciertos elementos de los contenedores se representan de manera predeterminada, es necesario utilizar la posición de atributo para colocar el nuevo elemento en el que tenía que ir. Sin embargo, al experimentar con diversos estilos, encontré un comportamiento diferente entre IE7 e IE8 al usar un contenedor div con una posición relativa, y un elemento secundario con una posición absoluta. Observe las Imágenes:

IE7:

IE8:

Quería mover el contenedor dev 170 pixeles hacia la izquierda, y lo que tuve que hacer es asignarle una posición relativa y asignar el atributo izquierdo a “-170″, el cual permite que el elemento muestre correctamente en ambos browsers. Sin embargo, solo por curiosidad, di al elemente hijo una posición absoluta y asigne tanto al atributo “Top” y “Left” para que heredaran “inherit”. El elemento fue colocado muy distante sobre su izquierda en IE8, así que ajuste el atributo izquierdo del elemento Padre a “-85″ lo cual resulto en las imágenes que ustedes pueden observar en la parte de arriba.

Por supuesto, tuve que salir de mi manera de romper el CSS, pero no me esperaba los navegadores interpretaran la “herencia” de manera diferente. Por supuesto, la eliminación de la posición absoluta en el Hijo o estableciendo su atributo de la izquierda a cero píxeles corrige el problema, pero ayudó a ilustrar para mí lo importante que es poner a prueba sus estilos de tantos exploradores como sea razonablemente posible. Claro, usted no puede codificar todas las situaciones, pero se puede intentar!

Hay un gran artículo que cubre las diferencias entre IE6, IE7 e IE8 por Louis Lazaris, Diferencias CSS en Internet Explorer 6, 7 y 8, y siempre www.quirksmode.org, documenta las diferencias entre Internet Explorer y otros navegadores.

Tags: , , ,


CSS Issue: 100% Height on a Div Tag

Here at Topline, I personally tend to spend most of my time writing C# code and T-SQL. In the last year or two, however, in a game of tag that I didn’t realize I was playing, I have become “it” when it comes to UI design. As a result, I have spent a lot of evenings learning CSS, and, contrary to what I supposed at the outset, I have grown to enjoy quite a bit. That being said, I am still learning and from time to time I encounter new and earth-shattering principles off CSS design that I have somehow missed before. This is especially true of using CSS for positioning and not just to change individual tag appearance.


In any case, such an epiphany happened to me this week. To give some background, while trying to add a different skin to a previously designed website for my brother-in-law, I was converting it from the dreaded table layout to use CSS Positioning. I was attempting to do a fairly standard layout which would consist of the following:

  • A Header
  • A Body
  • A Footer


A very simplified version of my HTML would look like this:

<html>
    <head>Head stuff Here</head>
    <body>
        <div id="dvContainer">
            <div id="dvHeader">Header Here</div>
            <div id="dvBody">
                <div id="dvMenu">Menu Here</div>
                <div id="dvContent">Content Here</div>
            </div>
            <div id="dvFooter">Footer Here</div>
        </div>
    </body>
</html>

Well, that all seems straightforward enough. I defined an external CSS file, added a reference to it on the page and started changing the CSS so that the entire site would look like a million bucks …. and frankly, it did. Then my whole world came crashing down on me. I had been working on the site at home using my strange little monitor. One morning when I came in to work, I decided to pull it up on my humongous monitor there just to see how it would look and I was horrified to see the result. At home, on all of the pages the content was long enough to push the footer past the bottom of my screen. At work however, the content ended up only going halfway down the page, which made the footer seem to float around in the middle of the screen as if it were trying to attack the header in some sort of ill-conceived CSS Coup d’etat.


It seemed that the problem should be easy enough to fix though, so that night I did a little research about getting the footer to stay at the bottom of the page, which is related but the subject of another post. When I implemented the fix though which, among other things, involved setting the “dvContainer” min-height to 100% and the “dvBody” style min-height to 100% in my stylesheet (along with a couple of other styles to the header and footer which I won’t go into here), the hight simply would not change.


No matter what I did, I could not get “dvContainer” to actually extend to 100% of height of the screen. Finally, I realized that the crux of my problem had to do with the way that percentage settings work in CSS. In essence, when you set something to be a percentage height, you are telling the browser that it should be XX% of whatever the tag happens to be inside of. So, if I had the following markup:

<div id="container" style="height: 250px;">
    <div id="coolStuff" style="height: 100%">Cool Stuff Here</div>
</div>

You might think that the “coolStuff” div tag would be 100% of the screen, but in actuality, the “coolStuff” div tag would only be 250 pixels tall because it is only going to be 100% of the height of the box that it is inside of. For the most part, I think that the majority of people doing CSS Development already knew this (although if you didn’t I hope that you will revere me from now on). What some people might not know … and I certainly didn’t, is that the body and the HTML tag are included in this. In other words, “body”s are people containers too.


This might sound a little circular, but the body tag is only going to be as tall as it needs to be to hold whatever is inside of it and setting whatever is inside of it to a height of 100% will only make it as tall as as it needs to be to fit inside the body which, as you recall, is only big enough to fit whatever was inside of the body before its height was set to 100% to begin with. Seriously, “Who’s on first?”


Let me try again, if you only have enough content to extend halfway down your page, that is how tall the body tag will be. Setting the height of the “dvContainer” tag to 100% didn’t do anything because it was only going to be as tall as the body and html tags which had already been set just high enough to hold all of the content on my page. The solution was to set the min-height of both the “body” and “html” tags to 100% too. After I did that viola … my container and my body tags also extended to the bottom of the page and it looks great again.


This leaves us with two “Morals of the Story”

  1. The “body” and “html” tags are actually containers too and should be treated as such. If you want anything else on the page to cover 100% of the viewable area you need to start by setting the styles correctly there.
  2. Don’t spend your spare time redesigning websites for your brother-in-law.

Tags: , , , ,