Hello!
There is a line in which there are line elements and between them text. Text may change dynamically. How to make it so that when changing the text, the elements did not move to the left and to the right but were in the same place, regardless of the length of the text between them.

<div> <select> <option value="+7">Россия</option> <option value="+375">Белоруссия</option> </select> <span id="country_code_label"></span> <input type="text" name="phone"> //Этот элемент будет сдвигаться, если в country_code_label будет текст разной длины. Нужно его как то зафиксировать. </div> 

3 answers 3

There are 2 options:

1) The length of the string is known - you can set the width for the country code and align it in the right direction (for example, to the right)

But

2) It is more logical and easier to insert this code into the input itself using a mask ( see example )

Thus, it is possible to perform validation on the client, to avoid validation checks on the backend, it is easier to parse the string.

You also need a script that reacts to the change select.

 $('.div2 input').mask(" (+375) 999-99-99"); 
 #country_code_label { display: inline-block; width : 3em; text-align: right; } .div1 { display: block; margin-bottom: 20px } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/jquery.maskedinput/1.4.1/jquery.maskedinput.min.js"></script> <div class="div1"> <select> <option value="+7">Россия</option> <option value="+375">Белоруссия</option> </select> <span id="country_code_label">+375</span> <input type="text" name="phone"> <!--Этот элемент будет сдвигаться, если в country_code_label будет текст разной длины. Нужно его как то зафиксировать. --> </div> <div class='div2'> <div> <h2>Можно так же повесить маску на ввод</h2> <h3>И менять код для страны при изменении select-а</h3> </div> <select> <option value="+7">Россия</option> <option value="+375">Белоруссия</option> </select> <!-- <span id="country_code_label"></span> --> <input type="text" name="phone"> <!--Этот элемент будет сдвигаться, если в country_code_label будет текст разной длины. Нужно его как то зафиксировать. --> </div> 

    somehow so probably:

     #country_code_label{ display:inline-block; max-width:30px; min-width:30px; overflow:hidden; } 
     <div> <select> <option value="+7">Россия</option> <option value="+375">Белоруссия</option> </select> <span id="country_code_label">sergargaergaergaergaer</span> <input type="text" name="phone"> //Этот элемент будет сдвигаться, если в country_code_label будет текст разной длины. Нужно его как то зафиксировать. </div> 

      If you decide head-on, then you need position: relative for the parent <div> and position: absolute for <input> .