使 div 向右浮动,同时保持换行

Make div float right while keeping line breaks

我正在尝试在 HTML 中创建以下模式:

CellA        CellB
             CellC
CellD        CellE
             CellF

我正在尝试混合使用 div 和 span 来执行此操作。我在 div 中创建了 CellC,因为浏览器总是在 div (Source) 前后放置换行符。我还给这个 div CSS 属性 float: right 这样它就会出现在右边(如上所示)。让它正确浮动是有效的,但我认为通过这样做我删除了 div 的默认 属性,我认为它是 display: block,换行符。即使我手动添加这个属性,它也没有影响。

这是我正在尝试的代码 (Along with a fiddle):

HTML

<div>CellA
  <span class="floatRight">CellB</span>
</div>
<div class="both">
  CellC
</div>

<div>CellD
  <span class="floatRight">CellE</span>
</div>
<div class="both">
  CellF
</div>

CSS

.floatRight { float:right;}
.both {float: right; display: block;}

上面的代码将使我的输出看起来像这样:

CellA        CellB
CellD   CellECellC
             CellF

将以下样式添加到两者 class

.both { 
    float: right; 
    display: block; 
    width: 100%;  
    text-align: right; 
}

如果您可以更改 HTML 结构,那么这种方法对您来说会很容易:

HTML

<div class="clearfix">
    <div class="left">
        Cell A
    </div>
    <div class="right">
        <div>
            Cell B
        </div>
        <div>
            Cell C
        </div>
    </div>
</div>
<div class="clearfix">
    <div class="left">
        Cell D
    </div>
    <div class="right">
        <div>
            Cell E
        </div>
        <div>
            Cell F
        </div>
    </div>
</div>

CSS:

.right {
    float: right;
}

.left {
    float: left;
}

.clearfix:after {
    content: "";
    clear: both;
    display: block
}

演示:https://jsfiddle.net/j0eqtzn2/2/

为什么要使用浮动?如果没有 "good" 使用浮动的理由,因为浮动会将元素从设计流程中移除。

请尝试使用 display inline-block

<html>
<head>
<title>foo</title>
<style>
.left {
width: 45%;
display: inline-block;
background-color: #0ff;
}
.right {
width: 45%;
display: inline-block;
background-color: #f00;
}
</style>
</head>

<body>
<div>
<div class="left">CellA</div> <div class="right">CellB</div>
<div class="left"></div>      <div class="right">CellC</div>
<div class="left">CellD</div> <div class="right">CellE</div>
<div class="left"></div>      <div class="right">CellF</div>
</div>
</body>
</html>

为您的问题添加另一种解决方案,您可以使用 flexbox 来完成此操作。 试试这个:

html:

<div class="flex-container">
  <div class="item">CellA</div>
  <div class="item">CellB</div>
  <div class="item">CellC</div>
  <div class="item">CellD</div>
  <div class="item">CellE</div>
  <div class="item">CellF</div>
</div>

css:

.flex-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  width: 100%;
}

.item:nth-child(3n) {
  width: 100%;
  text-align: right;
  color: red;
}

Demo

但是如果你不能使用 flexbox,@Jaspreet Singh 的回答是正确的。

如果你在这里使用 DL 而不是 DIV 那么这对你来说会很容易。因为它看起来像标题和描述

这是演示

[在此处查看演示][1]

[1]: https://jsfiddle.net/j0eqtzn2/6/