How to align <div> elements perfectly?
I'm trying to emulate the main page of Facebook to improve my skills, but it's hard for me to try to align the username and password window with each other, this is what it looks like:
My HTML:
<body>
<div id="top_banner">
<div id="header">
<h1>facebull</h1>
</div>
<div id="login_info">
<div id="username_group">
<label for="username_field">Email or Phone?</label>
<input type="text" id="username_field">
</div>
<div id="password_group">
<label for="password_field">Password</label>
<input type="text" id="password_field">
<label>Forgot account?</label>
</div>
</div>
</div>
My CSS:
*{
margin:0px;
padding:0px;
}
input, label{
display:block;
}
#top_banner{
background-color:#3b5998;
color: #fff;
width:100%;
height: 100px;
}
#header{
line-height: 100px;
position: absolute;
margin-left: 100px;
}
#password_group{
margin-left: 80%;
}
#username_group{
margin-left: 70%;
}
#container{
background-color: #e9ebee;
}
I already tried using margin-top and line-heighton #username_group, but it does not work. Also, how can I make the code more efficient?
+4
3 answers
Use the flexbox for the parent to separate the sections (using justify-content: space-between) and align them vertically, and then use flex in the login / password area to align and separate these elements.
* {
margin: 0px;
padding: 0px;
}
input,
label {
display: block;
}
#top_banner {
background-color: #3b5998;
color: #fff;
}
#container {
background-color: #e9ebee;
}
/* SO edits */
#top_banner {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 2em;
box-sizing: border-box;
}
#login_info {
display: flex;
padding: 1em;
}
#username_group {
margin-right: 1em;
}<div id="top_banner">
<div id="header">
<h1>facebull</h1>
</div>
<div id="login_info">
<div id="username_group">
<label for="username_field">Email or Phone?</label>
<input type="text" id="username_field">
</div>
<div id="password_group">
<label for="password_field">Password</label>
<input type="text" id="password_field">
<label>Forgot account?</label>
</div>
</div>
</div>+2
