开发者

How to auto width a form element with CSS?

Lately i've been through a lot of times on a single situation problem:

I have a text input element in a web formulary, inside a bigger div with defined width.

Inside that bigger div, i'll put a span text like "Name: " and then i'll put the input.

I want the input to auto become as much as wider the space of the div that the span is not using.

The code would be something like this:

<div>
    <span>Name:</span>
    <input type="text" name="name" />
</div>

And the CSS:

div {
   width: 200px;
   display: block;
}

span {
   display: inline-block;
   font: 11px 'Lucida Sans', Verdana, Arial;
}

input {
   height: 20px;
   width: auto;
   display: block;
}

I've been doing some research, but i seem unable to find a precise solution for this problem.

So far i've been skipping this problem by putting a inline style defining a different width for each element. But if i change the font, size, or whatever, it'll explode.

I don't like to build a fortress wall and leave it full of holes for snipers. That's why i'm looking for help :)

If you guys have any suggestion, solution or wo开发者_运维技巧rkaround way, I'd be glad to know. =D Thanks.


Semantically it's better to use label tags for this purpose:

<label>Name:</label>

Concerning your question, take a look at the CSS3 flexible box model: http://hacks.mozilla.org/2010/04/the-css-3-flexible-box-model/

Or if you prefer a video: http://www.youtube.com/watch?v=-OubGOxKa5I

At the time of writing, Mozilla and Webkit support this and there is a fallback for other browsers: https://github.com/doctyper/flexie


Sorry, but it's not possible with that markup. Actually the only way to do it is to shudder use tables (or display: table-cell, etc but that doesn't work in IE7 or earlier). It also generally looks better to have all the inputs aligned, don't you think?


Change display: block to display: inline for input and I think it should work.

Here is an example http://jsfiddle.net/KYvzM/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜