2017-03-21 177 views
2

有很多是方法来完成固定宽度的标签时,相应的表单控件是在其他一些节点:修复宽度标签内

<label for="foo">Text</label> 
<input id="foo"> 

不过,我一直在努力寻找一种明智的办法做到这一点,当窗体控件标签:

<label>Text <input></label> 

我最好的尝试意味着采取的形式控制了网页流量从而与具有不同高度的项目突破,如:

label{ 
 
    display: block; 
 
    position: relative; 
 
    margin: 1em; 
 
    padding: 1em; 
 
    width: 9em; 
 
    background-color: azure; 
 
} 
 
input, textarea{ 
 
    position: absolute; 
 
    top: 1em; 
 
    left: 11em; 
 
    width: 15em; 
 
} 
 
textarea{ 
 
    height: 8em; 
 
}
<div> 
 
    <label>Short <textarea></textarea></label> 
 
</div> 
 
<div> 
 
    <label>This is a very long label text <input></label> 
 
</div> 
 
<div> 
 
    <label>Average sized <input></label> 
 
</div>

鉴于这种HTML标记,是有可垂直扩展需要,既为标签和控制的任何其他相当简单的只CSS-技术?

回答

1

取决于你真正想要它看起来。

使用flex会浮现在脑海。

下面是一个简单的测试:

label{ 
 
    display: flex; 
 
    position: relative; 
 
    margin: 1em; 
 
    padding: 1em; 
 
    width:23em; 
 
    background-color: azure; 
 
} 
 

 
input, textarea{ 
 
    font:inherit; 
 
    width: 15em; 
 
    margin-left:auto; 
 
    flex:none; 
 
    box-sizing:border-box; 
 
} 
 

 
textarea{ 
 
    height: 8em; 
 
}
<div> 
 
    <label>Short <textarea></textarea></label> 
 
</div> 
 

 
<div> 
 
    <label>This is a very long label text <input></label> 
 
</div> 
 

 
<div> 
 
    <label>Average sized <input></label> 
 
</div>

0

可以使用display: tabledisplay: table-cell。它几乎与全线

label{ 
 
    display: table; 
 
    position: relative; 
 
    margin-top: 20px ; 
 
    padding: 10px; 
 
    width: 300px; 
 
    background-color: azure; 
 
} 
 
label > span { 
 
    width: 100px; 
 
    display: table-cell; 
 
    vertical-align: top; 
 
} 
 
label > input, textarea{ 
 
    display: table-cell; 
 
    width: 100%; 
 
} 
 
textarea{ 
 
    height: 100px; 
 
}
<div> 
 
    <label><span>Short</span> <textarea></textarea></label> 
 
</div> 
 
<div> 
 
    <label><span>This is a very long label text</span> <input></label> 
 
</div> 
 
<div> 
 
    <label><span>Average sized </span><input></label> 
 
</div>

所有的浏览器兼容