我的<main>
元素中有很多内容:
<main>
<h2>Sub heading</h2>
<p>Paragraph of text</p>
<h2>Sub heading</h2>
<p>Paragraph of text</p>
<h2>Sub heading</h2>
<p>Paragraph of text</p>
</main>
我想使用以下CSS在<main>
元素内创建两列布局的外观:
main {
overflow:auto;
}
h2 {
float:left;
width:50%;
}
p {
float:right;
width:50%;
}
我期待h2与段落的顶部对齐。但他们没有。第二个标题与第二个标题不一致,因此它们都不合规定。见图。
我该如何解决这个问题?或者我是否必须将每个H2和相应的文本放入div行,并在每行内部左侧div和右侧div?
答案 0 :(得分:3)
你有不同的选择:
1-添加clear:both或clear:右边的h2元素。
2-为每行添加div包装
.clearfix{
clear: both;
}
<div class="clearfix">
<h2>Sub heading</h2>
<p>Paragraph of text</p>
</div>
3-在包装div之后添加清除(这是如何做到twitter-bootstrap)
.clearAfter:after{
clear : both;
display: block;
content: '';
}
<div class="clearAfter">
<h2>Sub heading</h2>
<p>Paragraph of text</p>
</div>
<div class="clearAfter">
<h2>Sub heading</h2>
<p>Paragraph of text</p>
</div>
<div class="clearAfter">
<h2>Sub heading</h2>
<p>Paragraph of text</p>
</div>
我更喜欢第三种选择,因为你可以在不破坏布局的情况下更改内部内容。
答案 1 :(得分:1)
您需要清除每个新标题的浮动。您可以通过将clear:right;
(或clear:both;
)添加到h2
规则来实现这一目标。
main {
overflow:auto;
}
h2 {
float:left;
width:50%;
clear:right;
}
p {
float:right;
width:50%;
}
<main>
<h2>Sub heading</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<h2>Sub heading</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<h2>Sub heading</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</main>