在li元素中清除float的问题

时间:2018-01-12 10:41:35

标签: html css

尝试在HTML&中重现以下内容CSS:

enter image description here

以下是我试图构建它的方法:



.layout ul > li {
  list-style: none;
}

.layout ul > li:nth-child(1n) > img {
    float: left;
}

.layout ul > li:nth-child(2n) > img {
    float: right;
    z-index: 9999;
}

<div class="layout">
  <ul>
    <li><img src="http://placeimg.com/120/80/grayscale" /></li>
    <li><img src="http://placeimg.com/120/80/grayscale" /></li>
    <li><img src="http://placeimg.com/120/80/grayscale" /></li>
    <li><img src="http://placeimg.com/120/80/grayscale" /></li>
  </ul>
</div>
&#13;
&#13;
&#13;

问题是,在应用clearfix时,它根本没有帮助。图像似乎排成一排。也许在li元素和clearfix方面有什么特别的东西?如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

你可以简单地考虑text-align属性和重叠的一些负余量(这将避免你所有的浮动问题)

&#13;
&#13;
.layout {
  width: 200px;
}

.layout ul {
  margin: 0;
  padding: 0;
}

.layout ul>li {
  list-style: none;
  margin-bottom: -20px;
  position: relative; /* don't forget this to be able to use z-index */
}

.layout ul>li {
  text-align: left;
}

.layout ul>li:nth-child(2n) {
  text-align: right;
  z-index: 999; 
}
&#13;
<div class="layout">
  <ul>
    <li><img src="http://placeimg.com/120/80/grayscale" /></li>
    <li><img src="http://placeimg.com/120/80/grayscale" /></li>
    <li><img src="http://placeimg.com/120/80/grayscale" /></li>
    <li><img src="http://placeimg.com/120/80/grayscale" /></li>
  </ul>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

尝试使用 转换 css属性

&#13;
&#13;
.layout ul {
  display: flex;
  flex-wrap: wrap;
  padding: 0;
  list-style: none;
  background: #ccc;
  padding: 20px;
  padding-left: 40px;
}

.layout ul>li {
  width: 50%;
  box-sizing: border-box;
  border: 5px solid #fff;
  margin-bottom: 10px;
}

.layout ul>li>img {
  width: 100%;
  max-width: 100%;
  display: block;
}

.layout ul>li:nth-child(even) {
  transform: translateY(50%) translateX(-20px);
}
&#13;
<div class="layout">
  <ul>
    <li><img src="http://placeimg.com/120/80/grayscale" /></li>
    <li><img src="http://placeimg.com/120/80/grayscale" /></li>
    <li><img src="http://placeimg.com/120/80/grayscale" /></li>
    <li><img src="http://placeimg.com/120/80/grayscale" /></li>
  </ul>
</div>
&#13;
&#13;
&#13;