How to truncate text in select box using CSS only

9.6k Views Asked by At

I have been trying to make this work for sometime but no success for two days now.

I need to truncate/hide the text in a select box in the middle of it using CSS only. The rest of the field (the right side) should remain blank/white and the background image should be last to the right. Problem to the solutions I have tried is that the width of the select box needs to be changed and in this case the width needs to stay unchanged in order to keep the background arrow at it's current location. Something like this:

enter image description here

Maybe someone would have a bright idea (JavaScript is not a possible option):

The HTML here:

<div class="dropdown">
    <select>
       <option value="">Some Text</option>
       <option value="">Some More Text2</option>
       <option value="">Some More More More Longer Text</option>
    </select>                                
</div>

And the CSS here:

.dropdown{
    width:150px;
    border: 1px solid #cfcfcf;
    height: auto;
    border-radius: 5px;
    padding:3px 4px 4px;
    position: relative;
    z-index: 0;
    overflow:hidden;
    }

.dropdown select{
    border: none;
    background-color: transparent;
    outline: none;
    padding: 1px 0 0 5px;
    width:165%;
    background: url(http://i57.tinypic.com/nnmgpy_th.png) no-repeat right;
background-position: 55%;
    }

JSFiddle here: http://jsfiddle.net/pazzesco/r6c9zcpc/7/

2

There are 2 best solutions below

1
On BEST ANSWER

Making this happen with a bit of CSS3 is going to be your best bet for now and the future.

Here is a fiddle showing a different technique, still using you're arrow:

http://jsfiddle.net/plastclens/16Ljd8s8/2/

/* this places an arbitrary element inside the dropdown but before it's children elements */
/* We use it to cover half the select box as well as display the custom arrow */
.dropdown:before {
    height:29px;
    width:75px;
    display:block;
    content:'';
    position:absolute;
    top:0;
    right:3px;
    background: url(http://i57.tinypic.com/nnmgpy_th.png) #fff no-repeat right;
     pointer-events:none;
}

A important but overlooked part is the pointer-events:none; line. It lets the clicks to this "overlay" go through it and to the select.

Here is another decent resource for a no-image approach: http://cssdeck.com/labs/styling-select-box-with-css3 You may have to adjust it a bit but you'll get the point

0
On

Styling dropdowns is kind of tricky sometimes. You could add some right-padding to the select to force the element's text to stop "inside" your background:

.dropdown select{
    border: none;
    background-color: transparent;
    outline: none;
    padding: 1px 0 0 5px;
    width:165%;
    background: url(http://i57.tinypic.com/nnmgpy_th.png) no-repeat right;
    background-position: 55%;
    padding-right: 80%;
}

JSFiddle