简体   繁体   中英

Justifying form elements to fill a div horizontally

I have the following 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. I have achieved this with absolute positioning and floating, but surely, somehow, there is a way to use text-align to do this. 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. On the other hand, if you set text-align on the containing <div> , then everything inside the <div> will shove over to the right.

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. And then you can size the elements accordingly, using eg flexbox.

For example, to make the <input> fill the rest of the width:

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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