html - 使用 5 个元素创建 X 形状布局

标签 html css css-float

所以我的任务是将 5 个 div 对齐以放置在 X 位置:

body{
  height:300px;
  width: 300px;
}

div{
  height:100px;
  width:100px;
  float:left;
  background:black;
  overflow: none;
}

div:nth-child(2) {
    margin-left: 100px;
}
div:nth-child(3) {
    margin-left: 100px;
    margin-right: 100px;
}
div:nth-child(5) {
    margin-left: 100px;
}
<div>
</div>
<div>
</div>
<div>
</div>
<div>
</div>
<div>
</div>

正如你所看到的,我已经将它们对齐了。我不能使用任何其他附加元素,只能使用 5 个 div。但我有一种感觉,有一个更优雅的解决方案,更少的 css 行。很高兴看到最好的解决方案:)

最佳答案

body {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;  /* align items to edges, horizontally */
  align-content: space-between;    /* align items to edges, vertically */
  height: 300px;
  width: 300px;
}

div {
  height: 100px;
  width: 100px;
  background: black;
}

div:nth-child(2) {
  position: relative;              /* in-flow positioning */
  top: 50%;
  transform: translateY(-50%);
}
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

jsFiddle

关于html - 使用 5 个元素创建 X 形状布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42402722/

相关文章:

javascript - slideToggle 以前显示的元素没有 next()

css 表格与 bootstrap 不一致

html - 无法清除响应式布局中的 float ,冗长的内容框将其他人推倒

javascript - JS删除div内容并编写新代码

html - 是否存在一个完全没有意义的字符实体?

jQuery Quicksand 插件没有得到正确的位置

html - 使用 HTML 和 CSS,如何使图像与水平线垂直对齐?

css - float div 之间的均匀间距

CSS全宽减边距左div,20px同行右div

html - 如何使用纯 CSS 在 HTML 元素之上创建带轮廓的三 Angular 形提示?