为什么浮点div的顶部不与父div对齐?

时间:2013-06-19 02:46:49

标签: css html css-float

我正在尝试创建一个页面的一部分,其中两个文本div彼此对齐,但一个浮动到另一个的右侧。无论我尝试什么,浮动div似乎在开始之前留下一行空白文本。

http://jsfiddle.net/7MpYj/

处小提琴

以下是Chrome(和Safari)中的内容:

enter image description here

我玩边缘,填充,垂直对齐,似乎没有任何东西摆脱两者之间的空白。

CSS是:

body {
  font-family: sans-serif;
  font-size: 13px;
}
div.sidebar {
  width: 300px;
  float: right;
  background: pink;
}
div.maincolumn {
  background: #aaffaa;
}
div.clear {
  clear: right;
}

HTML是:

<div class="maincolumn">
  <div class="sidebar">
    <h3>Constitution</h3>
    We the People of the United States, in Order to form a more perfect
    Union, establish Justice, insure domestic Tranquility, provide for
    the common defence, promote the general Welfare, and secure the
    Blessings of Liberty to ourselves and our Posterity, do ordain and
    establish this Constitution for the United States of America.
  </div>
  <h3>Declaration</h3>
  When in the Course of human events, it becomes necessary for one
  people to dissolve the political bands which have connected them with
  another, and to assume among the powers of the earth, the separate and
  equal station to which the Laws of Nature and of Nature's God entitle
  them, a decent respect to the opinions of mankind requires that they
  should declare the causes which impel them to the separation.
  <p/>
  We hold these truths to be self-evident, that all men are created
  equal, that they are endowed by their Creator with certain unalienable
  Rights, that among these are Life, Liberty and the pursuit of
  Happiness.--That to secure these rights, Governments are instituted
  among Men, deriving their just powers from the consent of the
  governed, --That whenever any Form of Government becomes destructive
  of these ends, it is the Right of the People to alter or to abolish
  it, and to institute new Government, laying its foundation on such
  principles and organizing its powers in such form, as to them shall
  seem most likely to effect their Safety and Happiness.
</div>
<div class="clear">
  Edward by the grace of God King of England, lord of Ireland and
  duke of Aquitaine sends greetings to all to whom the present
  letters come. We have inspected the great charter of the lord
  Henry, late King of England, our father, concerning the liberties
  of England in these words:
</div>

是否有一些CSS魔法可以提升浮动div中的文本?

3 个答案:

答案 0 :(得分:0)

是。将overflow:auto添加到div.maincolumn

div.maincolumn {
    background: #aaffaa;
    overflow:auto;
}

<强> jsFiddle example

您的特定布局是block formatting context的示例以及overflow:auto如何恢复您所寻求的行为。

答案 1 :(得分:0)

将此添加到您的css:

div.sidebar h3 {
    margin-top:0;
}

这是一个小提琴:http://jsfiddle.net/7MpYj/3/

答案 2 :(得分:0)

尝试调整垂直对齐方式以将文本拉到顶部:

div.sidebar {
    vertical-align: top;
}