各种div的对齐方式

时间:2016-03-24 13:58:14

标签: html css web responsive-design alignment

我正在设计this layout - 请参阅第二张图片了解整体布局。

  • A高20px,必须占据整个屏幕宽度。
  • B高100px,也必须占据整个屏幕宽度。
  • C宽200px,必须占据屏幕的整个高度,不包括因A + B而高于它的120px。
  • D没有限制并适应窗口大小调整。

详细说明我目前面临的问题,请看第1张照片。

  • 如何确保B3的中心始终与div A中的文本中心对齐? B1-B4是我在B div中有4种不同的元素。 B1,B2和B4应保留在同一位置。唯一的“流体”部分是B3右/左边距的变化,使其保持中心对齐。

我目前的代码可以在this JSFiddle找到。

的index.html:

<div id="A">A</div>
<header>
  <!-- Header is B in the diagram -->
  <div id="B1">B1</div>
  <div id="B2">B2</div>
  <div id="B3">B3</div>
  <div id="B4">B4</div>
</header>
<div id="C">C</div>
<div id="D">D</div>

的style.css:

html, body {
    width: 100%;
    height: 100%;
}

#A{
    width:         100vw;
    height:        20px;
    background:    black;
    color: white;
    text-align: center;
}

header {
    height: 100px;
    width: 100%;
    background: #494949;
    color: white;
}

#B1 {
    width: 100px;
    height: 100px;
    margin-left: 5px;
    margin-right: 47px;
    float: left;
}

#B2 {
    float: left;
    margin-right: 60px;
}

#B3 {
    float: left;
    height: 75px;
    width: 580px;
    margin-top: 12.5px;
  text-align: center;
}

#B4 {
  float: right;
}

#C {
    height: 100%;
    width: 200px;
    float: left;
    position: fixed;
}

#D {
    background-color: #000000;
    float: left;
    margin-left: 200px;
    width: 100%;
    height: 100%;
    position: fixed;
    color: white;
}

我在评论中有一个关于我的意思的视频。另外,我想指出的是,我实际上并没有按字母顺序命名div,只是为了这个例子。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

如果您希望B3与A的中心对齐,则不能在B1和B2上使用float: left,因为它会在右侧移动B3的中心。我现在找到的唯一方法是在B1,B2和B4上使用绝对定位:

header {
    height: 100px;
    background: #494949;
    color: white;
    position: relative;
}

#B1, #B2, #B4 {
  width: 100px;
  height: 100px;
}

#B1 {
  position: absolute;
  top: 0px;
  left: 5px;
}

#B2 {
  position: absolute;
  top: 0px;
  left: 150px;
}

#B3 {
  text-align: center;
}

#B4 {
  position: absolute;
  top: 0px;
  right: 0px;
}

See demo here(可视化的附加颜色)。

但要小心,我的B3上的文字很大,它会在B1,B2或B4之下。为避免这种情况,您可以在B3的左侧和右侧添加填充。但它必须在两侧都是相同的值,否则B3的中心将不再与A的中心对齐。

我一直在寻找没有绝对定位的解决方案(因为我不喜欢它)......