简体   繁体   English

对齐表单元素以水平填充div

[英]Justifying form elements to fill a div horizontally

I have the following div: 我有以下div:

<div>
    <label for="ctl00_cph_address">Address</label>
    <input name="ctl00$cph$address" type="text" id="ctl00_cph_address" class="required text">
    <a id="ctl00_cph_addCcContact">Add</a>
    <span id="ctl00_cph_addressrequiredValidator" style="display: none;"></span>
    <span id="ctl00_cph_addressValidator" style="display: none;"></span>
</div>

I would like the label to be fixed width and right aligned, and this is normally easy, but what is near impossible is to get the addCcContact anchor to right align to the right side of the containing div. 我希望标签固定宽度并右对齐,这通常很容易,但是几乎不可能实现的是将addCcContact锚点右对齐到包含div的右侧。 I have achieved this with absolute positioning and floating, but surely, somehow, there is a way to use text-align to do this. 我已经通过绝对定位和浮动实现了这一点,但是可以肯定的是,有一种方法可以使用text-align来做到这一点。 Why is this so difficult? 为什么这么难?

The problem is if you set the text-align on the <a> it will correctly right-align the text inside the <a> element , but the <a> will still only take up the space it needs, and it will flow immediately after the input. 问题是,如果在<a>上设置text-align ,它将正确地<a>元素内的文本右对齐,但是<a>仍仅占用所需的空间,并且会立即流动输入后。 On the other hand, if you set text-align on the containing <div> , then everything inside the <div> will shove over to the right. 在另一方面,如果你设置text-align的含<div>那么一切都将里面<div>会推到右侧。

So you need to either use something like floating or positioning, or decide what you want to occupy the intervening space - the <input> , or an invisible element, or the <a> itself. 因此,您需要使用诸如浮动或定位之类的东西,或者确定要占据中间空间的内容- <input>或不可见元素,或<a>本身。 And then you can size the elements accordingly, using eg flexbox. 然后,您可以使用例如flexbox相应地调整元素的大小。

For example, to make the <input> fill the rest of the width: 例如,要使<input>填充其余宽度:

 div { display:flex; } input { flex:1 } 
 <div> <label for="ctl00_cph_address">Address</label> <input name="ctl00$cph$address" type="text" id="ctl00_cph_address" class="required text"> <a id="ctl00_cph_addCcContact">Add</a> <span id="ctl00_cph_addressrequiredValidator" style="display: none;"></span> <span id="ctl00_cph_addressValidator" style="display: none;"></span> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM