我有两个div元素,我想将它们对齐在同一行上。我或多或少都尝试过,但它们仍然相互影响。
我的代码如下
body {
background-color: #1b1b1b;
padding-left: 4%;
font-family: Helvetica;
}
h1 {
font-size: 40px;
color: white;
}
.important {
color: #5a92f0;
}
.left-side {
float: left;
display: inline-block;
margin: 10px;
padding-right: 50%;
}
.signup {
float: right;
background-color: white;
padding-left: 5%;
padding-right: 5%;
border-radius: 5px;
border: 1px solid white;
text-align: center;
display: inline-block;
margin: 10px;
}
.signup p {
font-size: 12px;
}
.signup h3 {
font-size: 17px;
}
.signup a {
color: #383737;
}
input[type=text],
select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #000;
border-radius: 4px;
box-sizing: border-box;
}
input[type=submit] {
width: 100%;
background-color: #5a92f0;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
<div>
<div class="left-side">
<h1> Lorem ipsum dolor sit. <span class="important">Lorem ipsum dolor sit.</span></h1>
</div>
<div class="signup">
<h2> Lorem ipsum dolor sit </h2>
<h3> Lorem ipsum dolor sit amet </h3>
<input id="email" name="emailaddress" placeholder="user@example.com" type="text">
<p>Lorem ipsum dolor sit amet, <a href="/terms">consectetur</a> adipiscing <a href="/privacy">elit sed</a>. </p>
<input value="Submit" type="submit">
<p>Lorem ipsum dolor? <a href="">Lorem ipsum</a></p>
</div>
</div>
发生的情况是一个div显示在上方,而另一个div则显示在第一个div下方居中。我希望它们彼此相对。
答案 0 :(得分:3)
我建议您考虑使用flexbox,它可以帮助解决对齐问题,并且可以很好地替代float。我将主体设置为显示:flex,将左右div设置为flex:1。
这应该有效:
<style>
body {
background-color: #1b1b1b;
padding-left: 4%;
font-family: Helvetica;
display: flex;
align-items: center;
}
h1 {
font-size: 40px;
color: white;
}
.important {
color: #5a92f0;
}
.left-side {
flex: 1;
display: inline-block;
margin: 10px;
padding-right: 10%;
}
.signup {
flex: 1;
background-color: white;
padding-left: 5%;
padding-right: 5%;
border-radius: 5px;
border: 1px solid white;
text-align: center;
display: inline-block;
margin: 10px;
}
.signup p {
font-size: 12px;
}
.signup h3 {
font-size: 17px;
}
.signup a {
color: #383737;
}
input[type=text],
select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #000;
border-radius: 4px;
box-sizing: border-box;
}
input[type=submit] {
width: 100%;
background-color: #5a92f0;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
</style>
<div class="left-side">
<h1> Lorem ipsum dolor sit. <span class="important">Lorem ipsum dolor sit.</span></h1>
</div>
<div class="signup">
<h2> Lorem ipsum dolor sit </h2>
<h3> Lorem ipsum dolor sit amet </h3>
<input id="email" name="emailaddress" placeholder="user@example.com" type="text">
<p>Lorem ipsum dolor sit amet, <a href="/terms">consectetur</a> adipiscing <a href="/privacy">elit sed</a>. </p>
<input value="Submit" type="submit">
<p>Lorem ipsum dolor? <a href="">Lorem ipsum</a></p>
</div>