mudFLAP
mudFLAP

Reputation: 77

How to indent text in a select drop down menu using CSS

How can I indent categories and endless sub categories that I have in a select drop down menu using CSS?

   1. Apple
   2. Arts & Entertainment
         1. Amusement
         2. Art
         3. Artists
               1. A
                     1. a1
                     2. a2
               2. B
               3. C
               4. D
   3. Automotive
   4. Network
   5. Server
   6. Web Design
         1. CSS
         2. HTML

Upvotes: 4

Views: 5093

Answers (2)

Yi Jiang
Yi Jiang

Reputation: 50165

You can't do this with the <select> element. You can't have endless nested subcategory like you suggest, only one, with <optgroup>. Styling will also be difficult as the ability to style form elements differs from browser to browser.

However, depending on your needs, the following solution might work:

For this, we are recreating the select element using HTML lists. The markup would look like this:

<div id="select">
    <p>Select your Answer</p>
    <ul>
        <li><a href="#">Apple</a></li>
        <li><a href="#">Arts and Entertainment</a>
            <ul>
                <li><a href="#">Amusement</a></li>
                <li><a href="#">Art</a></li>
                <li><a href="#">Artist</a>
                    <ul>
                        <li><a href="#">A</a></li>
                        <li><a href="#">B</a></li>
                    </ul></li>
            </ul>
        </li>
    </ul>
</div>

Then, with CSS, style it such that it fits your purpose:

#select {
    border: 1px solid #999;
    background-color: rgba(0, 0, 0, 0.1);
    position: absolute;
    width: 300px;
    font-family: Arial, sans-serif;
    font-size: 11px;
}

#select:hover {
    background-color: #efefef;
}

#select > ul {
    display: none;
    list-style: none;
}

#select:hover > ul {
    display: block;
}

#select > ul ul {
    margin-left: 20px;
}

#select > ul a, #select > p {
    display: block;
    padding: 3px 8px 4px;
    color: #333;
    text-decoration: none;
}

#select > ul a:hover {
    background-color: #ddd;
}

Play around with it here: http://jsfiddle.net/thHFS/

Upvotes: 2

Topera
Topera

Reputation: 12389

If you use elements (tags) to mount the drop down structure, you can do this:

HTML

<div class="menu">
    <div>
        1. Apple
    </div>
    <div>
        2. Arts
        <div>2.1 Foo</div>
        <div>2.2 Bar</div>
    </div>
    <div>
        3. Auto
    </div>
</div>

CSS

.menu div {
    padding-left: 30px;
}

The .menu div selector takes all divs inside div with "menu" class. They are nested, so paddings are summed automatically.

I've tested in jsfiddle (here) and works ok.

Upvotes: 0

Related Questions