@Deedeem, it would help if you gave us a link to your project or provided your code so we can see what you have. Anyway, there are several ways to go about this.
Depends on what you mean by align.
Not sure I would call using Bootstrap “cheating”, but you are right, it is good to learn how to do it yourself.
Your first step is to make sure your container is full width. After that, let’s look at several possibilites.
I. Flexbox
This one is pretty easy. In fact, centering anything with flexbox is easy, that’s why I mention this first. Create your container, and then make the form take up full width. You can then assign a width to the inputs.
<div class="container">
<form action="">
<input type="text">
<input type="text">
<textarea name="" id="" cols="30" rows="10"></textarea>
</form>
</div>
form {
width: 100%; /* make the form width of container */
display: flex;
flex-direction: column; /* make the form elements stack vertical instead of inline */
align-items: center; /* center the items horizontally */
}
input, textarea {
width: 40%; /* assign width to inputs and they will be centered inside the form */
}
You can also do this another way, where you assign the width to the form, make the inputs the full width of the form, and then use flexbox on the container.
.container {
height: 100vh;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
}
form {
width: 40%;
}
input, textarea {
width: 100%;
}
It all depends on which structure works best for your page. I would strongly suggest learning flexbox as it is almost always a guaranteed way to horizontally and/or vertically center any element.
II. Text Align Center
This is a somewhat hacky solution, but it works very well in certain instances and is pretty easy (unless you have to have several nested layers of centered elements).
This solution is extremely helpful when you don’t know the width of an element. display: inline-block
shrinks the container to whatever dimensions the child elements are. That is incredibly useful, but it is also ridiculously simple to center–just put text-align
on the parent:
.container {
height: 100vh;
width: 100%;
text-align: center;
}
form {
display: inline-block;
}
input, textarea {
width: 60%;
}
III. Margin Auto
@owel beat me to this, but I’ll provide an example anyway for the sake of a complete answer.
.container {
height: 100vh;
width: 100%;
text-align: center;
}
form {
width: 50%;
margin-left: auto;
margin-right: auto;
}
input, textarea {
width: 100%;
margin: 20px;
}
There are three simple ways to center practically anything. Margin auto is pretty simple, but doesn’t work all the time. Display inline-block
is extremely useful if you don’t know the width of the form. Flexbox can be used to practically center anything, so it is an essential tool for every developer to know.