I have two <input type="text">
and I need both to be centered as if they were one, let me explain:
There are two fields, one for name and one for last name, if I introduce for example "JUAN DIAZ", this text (which would be two input
) is visually centered in the yellow container, it is not exact, but it gives the appearance.
The problem is when the first name or last name do not have the same length, as I show in this image:
Is there a way to do it only with CSS, to center the text of both inputs as if they were one? You could also opt for JS. The only thing is that there must always be two (2) input
centered. It would be something like Excel's "combine and center" function, just to give an example.
This is the problem code:
input {
border: none;
background: transparent;
text-transform: uppercase;
font-weight: bold;
width: 150px;
}
.contenedor {
background-color: gray;
width: 350px;
padding: 4rem;
}
.centrar {
background-color: yellow;
padding: 1rem;
margin: 0 auto;
text-align: center
}
.nombre {
text-align: right;
}
.apellido {
text-align: left;
}
<div class="contenedor">
<div class="centrar">
<input class="nombre" type="text" /> <input class="apellido" type="text" />
</div>
<div>
Thank you for your comments.
What you are looking for can be done with a css variable (
--value
) and adding listeners to the inputs, so that when text is added to them, their size is modified according to the size of the text.We know that the size of both in total is
300px
therefore each one has150px
when they are in balance, then we can assume that each character adds4px
to the size of the input, saving the sizes of the texts entered in variables we can make calculations to assign size to the inputs to through the css variable.The code is as follows:
In this way the text is centered without affecting the difference in size between first and last name.
I hope you find it useful, greetings.
A solution could be the following:
nombre
and theapellido
, respectively.el.offsetWidth
to get the actual width of the textThen to determine the width that it should have
input
we must use the formula:IMPORTANT For the calculation of the text width to work correctly, it is necessary that both the
input
and theelementos ocultos
have the same font styles.Example:
My solution would be to create only one
input
in yourDOM
and manage by split and slice the obtaining of the names and surnamesWith
split
you separate the string you want into an array using the condition given as a parameter, which in this case would be ' ' ( white space ); and withslice
you get a part of the string according to the length of the full name, since it is possible to have one to N names. In fact, the tedious thing about this solution is that, handling the possible name options =/Tell us if it's what you need :)
I show you my example here that you can put code
And the photo of the result
Remember that if you use bootstrap you have to include the css and js libraries