如何对齐多个浮动元素

How to align multiple floating elements

我想正确对齐两个元素(A 和 C):

<div>
    <div class="a">A</div>
    <div class="b">B</div>
    <div class="c">C</div>
    <div class="d">D</div>
</div>

我的样式表:

.a, .b {
    float: left;
    clear: left;
    width: 40%;
}
.c, .d {
    float: right;
    clear: right;
    width: 40%;
}

但是,这会导致:

我想这样对齐 A 和 C:

说明问题的 JSFiddle:http://jsfiddle.net/foy79wz8/

有什么办法可以解决这个问题吗?

注意:由于HTML代码是第三方软件制作的,所以无法更改元素顺序。我只能指定自定义 CSS 样式表。

尝试使用绝对定位元素。

这是我的代码:

body > div {
    overflow: hidden;
    background: #faf;
    width: 100%;
    height: 60px;
    position: relative;
}
.a, .b, .c, .d{
    position: absolute;
    width: 40%;
    height: 20px;
}

.a{
    top: 0;
    left: 0;
}
.b{
    left: 0;
    top: 20px;
}
.c{
    top: 0;
    right:0;
}
.d{
    top: 20px;
    right: 0;
}

见下文fiddle

http://jsfiddle.net/foy79wz8/14/

代码片段如下,我稍微修改了一下布局,

body > div {
    overflow: hidden;
    background: #faf;
}
.a, .b {
    float: left;
    clear: left;
    width: 40%;
}
.c, .d {
    float: right;
    clear: right;
    width: 40%;
}
.a {
    background: #faa;
}
.b {
    background: #ffa;
}
.c {
    background: #afa;
}
.d {
    background: #aaf;
}
.inlinee{display:inline-block;float:left;width:50%;}
<div><div class="inlinee">
    <div class="a">A</div>
    <div class="b">B</div></div>
    <div class="inlinee">
    <div class="c">C</div>
        <div class="d">D</div></div>
</div>

给你...这有效..只需将此代码复制下来。它完美运行:

    body > div {
    overflow: hidden;
    background: #faf;
    width: 100%;
    height: 40px;
    position: relative;
}
.a, .b, .c, .d{
    position: absolute;
    width: 40%;
    height: 20px;
}

.a{
    top: 0;
    left: 0;
     background: #faa;
}
.b{
    left: 0;
    top: 20px;
   background: #ffa;
}
.c{
    top: 0;
    right:0;
    background: #afa;
}
.d{
    top: 20px;
    right: 0;
    background: #aaf;
}

https://jsfiddle.net/kamal1990/pz39a39c/

*{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

body > div {    
    background: #faf;   
}

div > div{
    display: inline-block;
    vertical-align: top;
    padding: 15px;
}

.a, .b {width: 40%;}
.c, .d {width: 40%;}

.a {background: #faa;}
.b {background: #ffa;}
.c {background: #afa;}
.d {background: #aaf;}


div > div:nth-child(even){
    margin-left: 20%;
}
<div>
    <div class="a">A</div><!--
    --><div class="b">B</div><!--
    --><div class="c">C</div><!--
    --><div class="d">D</div>
</div>

您可以使用 javascript 或 JQuery 进行此更改而无需修改 html 代码

你可以

  • 向左浮动 .a.b
  • 左清.b,为了防止与.a
  • 相邻
  • .c.d 显示为内联块
  • 在包装器上使用 text-align: right,以便使 .c.d 向右对齐
  • 在元素上恢复 text-align: left

body {
  text-align: right;
}
div {
  width: 40%;
  text-align: left;
  border: 1px solid;
}
.a, .b {
  float: left;
  clear: left;
}
.c, .d {
  display: inline-block;
}
<div class="a">A</div>
<div class="b">B</div>
<div class="c">C</div>
<div class="d">D</div>