这是我的代码(请参阅小提琴here):
<div class='container'>
<div class='hero-unit'>
<h2>Welcome</h2>
<p>Please log in</p>
<div id='login-box' class='pull-right control-group'>
<div class='clearfix'>
<input type='text' placeholder='Username' />
</div>
<div class='clearfix'>
<input type='password' placeholder='Password' />
</div>
<button type='button' class='btn btn-primary'>Log in</button>
</div>
</div>
</div>
我希望#login-box
拥有.pull-right
并与p
处于同一高度。我可以使用margin-top: -100px
但感觉不对。
如何#login-box
与p
处于同一高度,而无需对margin-top
进行硬编码?
答案 0 :(得分:57)
Float元素将在它们通常在布局中的行上呈现。要解决此问题,您有两种选择:
在登录框后移动标题和p:
<div class='container'>
<div class='hero-unit'>
<div id='login-box' class='pull-right control-group'>
<div class='clearfix'>
<input type='text' placeholder='Username' />
</div>
<div class='clearfix'>
<input type='password' placeholder='Password' />
</div>
<button type='button' class='btn btn-primary'>Log in</button>
</div>
<h2>Welcome</h2>
<p>Please log in</p>
</div>
</div>
或者将左侧块放在左下方的div中,并在底部添加一个clearfix
<div class='container'>
<div class='hero-unit'>
<div class="pull-left">
<h2>Welcome</h2>
<p>Please log in</p>
</div>
<div id='login-box' class='pull-right control-group'>
<div class='clearfix'>
<input type='text' placeholder='Username' />
</div>
<div class='clearfix'>
<input type='password' placeholder='Password' />
</div>
<button type='button' class='btn btn-primary'>Log in</button>
</div>
<div class="clearfix"></div>
</div>
</div>
答案 1 :(得分:3)
只需在#login-box
之前放<h2>Welcome</h2>
即可。
<div class='container'>
<div class='hero-unit'>
<div id='login-box' class='pull-right control-group'>
<div class='clearfix'>
<input type='text' placeholder='Username' />
</div>
<div class='clearfix'>
<input type='password' placeholder='Password' />
</div>
<button type='button' class='btn btn-primary'>Log in</button>
</div>
<h2>Welcome</h2>
<p>Please log in</p>
</div>
</div>
这里是jsfiddle http://jsfiddle.net/SyjjW/4/
答案 2 :(得分:0)
将h2保持在顶部,然后在p上向左拉并在登录框上向右拉
<div class='container'>
<div class='hero-unit'>
<h2>Welcome</h2>
<div class="pull-left">
<p>Please log in</p>
</div>
<div id='login-box' class='pull-right control-group'>
<div class='clearfix'>
<input type='text' placeholder='Username' />
</div>
<div class='clearfix'>
<input type='password' placeholder='Password' />
</div>
<button type='button' class='btn btn-primary'>Log in</button>
</div>
<div class="clearfix"></div>
</div>
</div>
浮动框上的默认垂直对齐是基线,因此“请登录”与“用户名”完全对齐(通过将拉向右更改为向左拉动来检查)。