CSS – Attribute selectors

What are attributes?

All HTML elements can have associated properties, called attributes. These attributes generally have values. Any number of attribute/value pairs can be used in an element’s tag – as long as they are separated by spaces. They may appear in any order.

Attribute selectors

Attribute selectors are used to select elements based on their attributes or attribute value. For example, you may want to select any image on an HTML page that is called “small.gif”. This could be done with the rule below, that will only target images with the chosen name:

 img[src="small.gif"] { border: 1px solid #000; }

There are four types of attribute selectors.

The first option is to select based on attribute. The example below will select an element (in this case “img”) with the relevant attribute. Examples could include:

img[title] { border: 1px solid #000; }
img[width] { border: 1px solid #000; }
img[alt] { border: 1px solid #000; }

The second option is to select based on value. The example below will select any image whose attribute (in this case “src”) has a value of “small.gif”.

 img[src="small.gif"] { border: 1px solid #000; }

The third method will select space separated instances of a value. The example below will select any image whose attribute (in this case “alt”) contains a space separated list of words – in this case any “alt” that includes the word “small”.

 img[alt~="small"] { border: 1px solid #000; }

The fourth method will select hyphen separated instances of a value. The example below will select any image whose attribute (in this case “title”) has a hyphen separated list – in this case any title that includes “small-”.

 img[title|="small"] { border: 1px solid #000; }

Attribute selectors are not supported by Windows Internet Explorer 5, 5.5 and 6 or Macintosh Internet Explorer 5. They are also not supported by earlier versions of Opera.

Source: http://css.maxdesign.com.au/selectutorial/selectors_attribute.htm

 

Redistribute your webpage contents to fit your browser width

Are you tired of dealing with different screen sizes for your web pages? Well, this information is for you.

I will show you some CSS tricks to help you reorganize a webpage depending on your browser window width.

We will start with a simple HTML 5 skeleton that includes a contents and a navigation section:

<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    /* we will add our style here on the next step */
  </style>
</head>
<body>
  <div role="main">
    <h1>This is the contents</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
       Nunc venenatis ante sed augue porttitor at volutpat felis
       consequat. Pellentesque eget neque vel erat cursus
       fermentum. Cras convallis eros malesuada lectus condimentum
       a semper eros sollicitudin. Phasellus bibendum, elit in
       facilisis volutpat, felis nisl venenatis mauris, non
       vestibulum diam urna id eros. Proin augue mauris, aliquam
       condimentum suscipit vel, semper sit amet orci. Pellentesque
       eleifend, sem in feugiat ultrices, lacus diam luctus turpis,
       quis malesuada dui risus et magna. Donec egestas, ligula in
       faucibus accumsan, lacus nibh condimentum urna, vel pulvinar
       nulla mi quis turpis. </p>
  </div>
  <nav role="navigation">
    <h2>This is the navigation.</h2>
    <ol>
      <li><a href="#">Option 1</a></li>
      <li><a href="#">Option 2</a></li>
      <li><a href="#">Option 3</a></li>
    </ol>
  </nav>
</body>
</html>

Pretty simple uh? Now, we will add some CSS between the style tags in the head section. This CSS will do the magic depending on our window width.

@media screen and (min-width: 30em) {
    body {
        display: table;
        caption-side: top;
    }
    [role="navigation"] {
        display: table-caption;
    }
    [role="navigation"] ol {
        display: table-row;
    }
    [role="navigation"] ol li {
        display: table-cell;
        padding: 0.5em;
    }
}

Try changing your browser size and see how your webpage redistributes itself to fit your contents and navigation section in a nice way.

So what happened? Well:

@media screen and (min-width: 30em) checks if media is a computer screen and it has a minimum width of 30 em’s. If both conditions are met, then:

body { display: table; caption-side: top; } treats the body contents as if it were a table, setting the caption-side to show on the top.

[role="navigation"] { display: table-caption; } uses an attribute selector to set the tag marked with the navigation role as the table caption, thus sending it to the top of the page.

[role="navigation"] ol { display: table-row; } sets the ol inside the tag marked with the navigation role to be treated as a table row, so in short, the ol will be displayed as a row.

Finally, [role="navigation"] ol li { display: table-cell; padding: 0.5em; } instructs the browser to treat every li inside an ol inside a tag marked with the  navigation role as a table cell. That is why the list items are displayed in a contiguous way. Just like cells in a table row.

And that’s it! When the first condition is not met (min-width: 30em) then the page shows as originally layed on the html. You can keep adding conditions depending on what you want to accomplish. You can find more conditions on the W3C webpage.

 

An easy to do CSS Horizontal Menu

Here it is. Start with a conventional item list like the following:

<ul class="hmenu">
    <li><a href="">Option 1</a></li>
    <li><a href="">Option 2</a></li>
    <li><a href="">Option 3</a></li>
    <li><a href="">Option 4</a></li>
    <li><a href="">Option 5</a></li>
</ul>

Don’t forget to add the class parameter to the ul tag – that will help us do the magic. The previous list is rendered in a regular browser like the following:

Now, add the following CSS to your file:

.hmenu {
    margin: 0;
    padding: 0;
    list-style-type: none;
    list-style-image: none;
}
.hmenu li {
    display: inline;
}
.hmenu a {
    background-color: #b0d3ee;
    color: #fff;
    padding: 0.5em 1em;
    text-decoration: none;
}
.hmenu a:hover {
    background-color: #62a9dd;
}

Tada! Our list turns into a beautiful menu:

The main trick here is done by the display: inline attribute. This will render the item list in a horizontal way. All other values are there to make it look fancier.

Enjoy.

Create a DNS zone file

An example master zone file for example.org (existing within /etc/namedb/master/example.org) is as follows:

$TTL 3600        ; 1 hour default TTL
example.org.    IN      SOA      ns1.example.org. admin.example.org. (
                                2006051501      ; Serial
                                10800           ; Refresh
                                3600            ; Retry
                                604800          ; Expire
                                300             ; Negative Response TTL
                        )

; DNS Servers
                IN      NS      ns1.example.org.
                IN      NS      ns2.example.org.

; MX Records
                IN      MX 10   mx.example.org.
                IN      MX 20   mail.example.org.

                IN      A       192.168.1.1

; Machine Names
localhost       IN      A       127.0.0.1
ns1             IN      A       192.168.1.2
ns2             IN      A       192.168.1.3
mx              IN      A       192.168.1.4
mail            IN      A       192.168.1.5

; Aliases
www             IN      CNAME   example.org.

Note that every hostname ending in a “.” is an exact hostname, whereas everything without a trailing “.” is relative to the origin. For example, ns1 is translated into ns1.example.org.

The format of a zone file follows:

recordname      IN recordtype   value

The most commonly used DNS records:

SOA
start of zone authority

NS
an authoritative name server

A
a host address

CNAME
the canonical name for an alias

MX
mail exchanger

PTR
a domain name pointer (used in reverse DNS)

example.org. IN SOA ns1.example.org. admin.example.org. (
                        2006051501      ; Serial
                        10800           ; Refresh after 3 hours
                        3600            ; Retry after 1 hour
                        604800          ; Expire after 1 week
                        300 )           ; Negative Response TTL
example.org.
the domain name, also the origin for this zone file.

ns1.example.org.
the primary/authoritative name server for this zone.

admin.example.org.
the responsible person for this zone, email address with “@” replaced. (<admin@example.org> becomes admin.example.org)

2006051501
the serial number of the file. This must be incremented each time the zone file is modified. Nowadays, many admins prefer a yyyymmddrr format for the serial number. 2006051501 would mean last modified 05/15/2006, the latter 01 being the first time the zone file has been modified this day. The serial number is important as it alerts slave name servers for a zone when it is updated.

       IN NS           ns1.example.org.

This is an NS entry. Every name server that is going to reply authoritatively for the zone must have one of these entries.

localhost       IN      A       127.0.0.1
ns1             IN      A       192.168.1.2
ns2             IN      A       192.168.1.3
mx              IN      A       192.168.1.4
mail            IN      A       192.168.1.5

The A record indicates machine names. As seen above, ns1.example.org would resolve to 192.168.1.2.

                IN      A       192.168.1.1

This line assigns IP address 192.168.1.1 to the current origin, in this case example.org.

www             IN CNAME        @

The canonical name record is usually used for giving aliases to a machine. In the example, www is aliased to the “master” machine whose name happens to be the same as the domain name example.org (192.168.1.1). CNAMEs can never be used together with another kind of record for the same hostname.

               IN MX   10      mail.example.org.

The MX record indicates which mail servers are responsible for handling incoming mail for the zone. mail.example.org is the hostname of a mail server, and 10 is the priority of that mail server.

One can have several mail servers, with priorities of 10, 20 and so on. A mail server attempting to deliver to example.org would first try the highest priority MX (the record with the lowest priority number), then the second highest, etc, until the mail can be properly delivered.

For in-addr.arpa zone files (reverse DNS), the same format is used, except with PTR entries instead of A or CNAME.

$TTL 3600

1.168.192.in-addr.arpa. IN SOA ns1.example.org. admin.example.org. (
                        2006051501      ; Serial
                        10800           ; Refresh
                        3600            ; Retry
                        604800          ; Expire
                        300 )           ; Negative Response TTL

        IN      NS      ns1.example.org.
        IN      NS      ns2.example.org.

1       IN      PTR     example.org.
2       IN      PTR     ns1.example.org.
3       IN      PTR     ns2.example.org.
4       IN      PTR     mx.example.org.
5       IN      PTR     mail.example.org.

This file gives the proper IP address to hostname mappings for the above fictitious domain.

It is worth noting that all names on the right side of a PTR record need to be fully qualified (i.e., end in a “.”).

Source: http://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/network-dns.html

 

Show User Library Directory in Mac OS X Lion

Show User ~/Library in OS X Lion

Launch Terminal from Spotlight or Launchpad > Utilities, and enter the following command to show the directory:

chflags nohidden ~/Library/

The users Library folder will immediately become visible. Reverting this back to the standard Lion setting is simple too:

Hide User ~/Library in OS X Lion (default setting)

This returns to the default setting of hiding the user Library directory:

chflags hidden ~/Library

Changes take effect immediately again, and Library becomes invisible to the user.

How to create a simple gradient in C#

Creating a simple gradient using two colors is very simple:

Rectangle rect = new Rectangle(0, 0, 100, 100);
LinearGradientBrush lgb = new LinearGradientBrush(rect, Color.White, Color.Blue, 90);
e.Graphics.FillRectangle(lgb, rect);

This code will generate a gradient in the given rectangle that goes from white to blue in a vertical way (see last parameter in constructor). In this case, e, is any class that encapsulates the System.Drawing.Graphics class. Once the gradient is ready, well, you have to actually draw it by calling the FillRectangle function.

You can use this gradient for images or printings or any other place where a regular Brush may fit.

Printing in C# – The easy way

Believe me, it is easy. As with any class, before we can use any of the Classes, Events and Objects available to us in the .Net Framework we need to import the Namespaces we need. For this we need but 3, the VB.Net counterpart only required 2 because VB.Net assumes the System Namespace, whereas C# isn’t so kind:

These 3 Namespaces contain everything we need for this class, so you will need to add the following lines to the top of your class file:

using System;
using System.Drawing;
using System.Drawing.Printing;

Now we have to inherit the PrintDocument Class. To do this, make the following change to the declaration of your class:

public class PCPrint : System.Drawing.Printing.PrintDocument
{

}

So now we have a shell to work with that inherits from the PrintDocument Class, so lets add some functionality and other code to our class. In our class we will have 2 properties, one to hold the text that we are printing, and one to hold the Font we will be using when printing our document. We will also add a variable to hold the current character we are working with. This is necessary for more than one page texts.

public Font PrinterFont { get; set; }
public string TextToPrint { get; set; }

// Static variable to hold the current character we're currently
// dealing with.
static int curChar;

Adding the Font property allows us to override the default font.

Next we will incorporate some Constructors for our class. Since we are inheriting from a separate class, we need to call the Constructor of the base class. This is done by using base(), this will call the Constructor of our base class, the PrintDocument Class:

public PCPrint() : base()
{
    //Set our Text property to an empty string
    TextToPrint = string.Empty;
}

public PCPrint(string str) : base()
{
    //Set our Text property value
    TextToPrint = str;
}

Now we have our Properties and our Constructors, next we will add a couple methods to our class. In our printing class we will be overriding 2 of the PrintDocument methods, those will be the OnBeginPrint method and the OnPrintPage method. In the OnBeginPrint method we will override the default font with the font we specify, and in the OnPrintPage we will be setting up the specifics of our page. We will be setting the following properties:

  • Page Size
  • Page Orientation (Landscape, Portrait)
  • Top Margin
  • Left Margin

First, the OnBeginPrint method, as with our Constructors we will need to call our base class’s OnBeginPrint method, then we can do our custom work:

/// <summary>
/// Override the default OnBeginPrint method of the PrintDocument Object
/// </summary>
/// <param name=e></param>
/// <remarks></remarks>
protected override void OnBeginPrint(System.Drawing.Printing.PrintEventArgs e)
{
    // Run base code
    base.OnBeginPrint(e);

    //Check to see if the user provided a font
    //if they didn't then we default to Times New Roman
    if (PrinterFont == null)
    {
        //Create the font we need
        PrinterFont = new Font("Times New Roman", 10);
    }
}

As you can see, here we call the base class’s OnBeginPrint method, then we check to see if a font was provided, if no one was, we default to Times New Roman. The OnPrintPage method is quite a bit larger and complex, this is where we will be doing the bulk of our work.

In this method we will be setting the size of the print area (the page size), we will determine if the user selected Landscape or Portrait as the print style, we will determine how many lines we are printing and how many lines will fit in our page size, and finally we will tell the printer whether we have more pages to print. As with our OnBeginPrint method, we will need to call our base class’s OnPrintPage method before doing our customizing of the method. Let’s take a look at our overridden OnPrintPage method:

/// <summary>
/// Override the default OnPrintPage method of the PrintDocument
/// </summary>
/// <param name=e></param>
/// <remarks>This provides the print logic for our document</remarks>
protected override void OnPrintPage(System.Drawing.Printing.PrintPageEventArgs e)
{
    // Run base code
    base.OnPrintPage(e);

    //Declare local variables needed

    int printHeight;
    int printWidth;
    int leftMargin;
    int rightMargin;
    Int32 lines;
    Int32 chars;

    //Set print area size and margins
    {
        printHeight = base.DefaultPageSettings.PaperSize.Height - base.DefaultPageSettings.Margins.Top - base.DefaultPageSettings.Margins.Bottom;
        printWidth = base.DefaultPageSettings.PaperSize.Width - base.DefaultPageSettings.Margins.Left - base.DefaultPageSettings.Margins.Right;
        leftMargin = base.DefaultPageSettings.Margins.Left;  //X
        rightMargin = base.DefaultPageSettings.Margins.Top;  //Y
    }

    //Check if the user selected to print in Landscape mode
    //if they did then we need to swap height/width parameters
    if (base.DefaultPageSettings.Landscape)
    {
        int tmp;
        tmp = printHeight;
        printHeight = printWidth;
        printWidth = tmp;
    }

    //Create a rectangle printing are for our document
    RectangleF printArea = new RectangleF(leftMargin, rightMargin, printWidth, printHeight);

    //Use the StringFormat class for the text layout of our document
    StringFormat format = new StringFormat(StringFormatFlags.LineLimit);

    //Fit as many characters as we can into the print area
    e.Graphics.MeasureString(TextToPrint.Substring(RemoveZeros(ref curChar)), PrinterFont, new SizeF(printWidth, printHeight), format, out chars, out lines);

    //Print the page
    e.Graphics.DrawString(TextToPrint.Substring(RemoveZeros(ref curChar)), PrinterFont, Brushes.Black, printArea, format);

    //Increase current char count
    curChar += chars;

    //Detemine if there is more text to print, if
    //there is the tell the printer there is more coming
    if (curChar < TextToPrint.Length)
    {
        e.HasMorePages = true;
    }
    else
    {
        e.HasMorePages = false;
        curChar = 0;
    }
}

You will notice that in this method we reference a function called RemoveZeros. This is the last function in our class, and it has an important role. We will create a function that will check our value, and if it’s a 0 (not the number, but a memory space with a value of zero – ascii 0 -) we will replace it with a 1 (ascii 1). Zero’s can cause bad things to happen when it comes to printing and determining page size and margins, so to alleviate that we use our RemoveZeros Function:

public int RemoveZeros(ref int value)
{
    //As 0 (ZERO) being sent to DrawString will create unexpected
    //problems when printing we need to search for the first
    //non-zero character in the string.
    while (TextToPrint[value] == '\0')
    {
        value++;
    }
    return value;
}

And there you have it, our completed printing class. Now I know some are asking “I see this class, but how do I use it?”. Well I’m glad you asked, this class is much easier to use than one would imagine. In your Form’s code I would create a procedure, lets name it printDocument, then inside that procedure we would create an instance of our printer class, set its properties (PrinterFont, TextToPrint), then issue a print command, like this:

public void PrintDocument()
{
    //Create an instance of our printer class
    PCPrint printer = new PCPrint();
    //Set the font we want to use
    printer.PrinterFont = new Font("Verdana", 10);
    //Set the TextToPrint property
    printer.TextToPrint = Textbox1.Text;
    //Issue print command
    printer.Print();
}

Some other functions and classes you may find useful are DrawRectangle, FillRectangle, Arc, Brushes and Pen. All these basic functions will help you get beautiful reports if you have the patience to put them together.

Based on Printing in C# by PsychoCoder

 

How to choose a printer using C#

You can assign a printer and other settings by using the basic PrintDocument and PrintDialog controls properties. Look at the next example:

if (printDialog.ShowDialog() == DialogResult.OK) {
    printDocument.PrinterSettings.PrinterName = printDialog.PrinterSettings.PrinterName;
    printDocument.PrinterSettings.Copies = printDialog.PrinterSettings.Copies;
}