Hi I am a beginner and trying to position a button
that sits inside a form
element on the bottom right of a container, but not able to do so. Please advise. Thank you.
Whether using the float:right;
or position: absolute;
, the button is being taken out of the container(from my understanding from the dev tool on Google Chrome).
HTML code
<section class="form-container">
<h1>Meme Generator</h1>
<p>Fill out the form to start creating memes!</p>
<form action="#">
<label for="img-url"
>Image URL
<input type="text" id="img-url" />
</label>
<label for="top-txt"
>Text On Top
<input type="text" id="top-txt" />
</label>
<label for="bottom-txt"
>Text On Bottom
<input type="text" id="bottom-txt" />
</label>
<button>Add Meme</button>
</form>
</section>
CSS code
/* Reset */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* Set core body defaults */
body {
min-height: 100vh;
line-height: 1.5;
}
/* Input buttons don't inherit font property */
/* Inherit fonts for inputs and buttons */
input, button {
font: inherit;
}
/* VARIABLES */
:root {
--spacing: 1rem;
}
/* GENERAL STYLE - MOBILE FIRST*/
body {
font-family: 'Roboto', Courier, monospace;
}
.form-container {
padding: var(--spacing);
background-color: rgba(245, 221, 194, 0.75);
min-width: 100%;
}
.form-container h1,
.form-container p {
text-align: center;
}
form {
position: relative;
}
form label {
display: block;
margin-top: var(--spacing);
}
label input {
display: block;
min-width: 100%;
}
form button {
margin-top: var(--spacing);
padding-left: var(--spacing);
padding-right: var(--spacing);
/* when setting absolute, it's being taken out of the .form-container */
/* position: absolute; */
}
2
Answers
You can set the form to
display: flex
and align vertically usingflex-direction: column
, then set the button toalign-self: flex-end
to be moved at the right side of the flex container.Here are the changes:
Now, to understand why
float
andposition: aboslute
do not have the effect that you would expect, let’s take a look a what these two actually do:float: "The element is removed from the normal flow of the page" MDN Docs
position: absolute "The element is removed from the normal document flow, and no space is created for the element in the page layout." MDN Docs
Solution #2: Clearing the float:
You can
clear
the float by appending an empty div that has theclear
property set toboth
which clears the "floating" and produces the result that you are looking for. Check this MDN article to understand howclear
works.Solution #3: Using
position:absolute
You can use
position: absolute
on the button, but you will have to tweak the code a bit. You will need to (1) remove theposition:relative
from the form and move it to theform-container
, add a bit of padding at the bottom and they play around with thebottom
andright
values of the absolutely positioned button to get the layout that you want:You could also set the height of the form container to lets say 50% and the form button float to left.
This is the code;