Menachem
Menachem

Reputation: 941

Set width of input field to width of original content (with CSS)

I'm trying to implement the following feature: A webpage with many lines such as Type.classname=com.long.qualified.class.Name, where the line corresponds to an entry in a Java properties file. Each such line references a file named (contextRoot)/.../path/.../Name.java.

I want to be able to copy the filename easily, so I can (in Eclipse) locate the source file referenced by the property. So, I'm making the package name a <label> and the class name an <input>, connecting them with a for. Then I added an onfocus to the class name, in which I do this.select(). I also added styling to make the text field not look like a text field, i.e. font, border:none, readonly (not CSS).

My first question is: how do I set the width of the text field to the full width of it's original content. Other questions had answers about adjusting the width dynamically - this is not an issue for me. Can it be done with CSS, or do I have to use javascript. There are over 1000 such lines, and I'd rather not use more script than I need to.

My second question is: am I doing these the hard way, and there's an easier way to accomplish my goal, or is this pretty much the way anyone else would do it?

Thanks.

Upvotes: 0

Views: 1482

Answers (1)

Billy Moat
Billy Moat

Reputation: 21050

You could possibly use the box-sizing property to achieve what you want.

http://jsfiddle.net/AjtCR/

Here's what browsers it's compatible with: http://caniuse.com/#search=box-sizing

​<div>
 <input type="text" />
</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

​div {
 width:200px;
 height:200px;
 background:#999;
 padding-top:50px;
}

input {
 -webkit-box-sizing: border-box;
 -moz-box-sizing: border-box;
 box-sizing: border-box;
 width:100%;
 padding:5px;
 border:1px solid #000;
}

Upvotes: 1

Related Questions