Make Even Divs Switch Floats

时间:2014-10-24 00:01:41

标签: html css css-float css-selectors

我遇到的问题是我有一个ID为“#flights”的div作为我的主要容器,我有一个div,类“.flight”是每个选项的容器,然后在.flight内部我有两个div,一个用于img,一个用于信息,并且在每个之后都是明确的:

<div class="flight">
    <div class="flight-img"></div>
    <div class="flight-heading">
        <h2>Shared Flights</h2>
        <p>The shared flight option is available for 1 to 5 people. This is our most economical flight. You will fly with other passengers that are booked that day.</p>
        <button>Book Now</button>
    </div>
</div>
<div class="clear"></div>

我的css是:

.flight-img {
    background: url(../img/flights.jpg) top left no-repeat;
    background-size: cover;
    width: 40%;
    height: 400px;
    float: left;

}


.flight-heading {
    width: 60%;
    float: left;
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

除了我想让他们在偶数孩子身上切换侧面(即.flight-img向右浮动和.flight-heading向左浮动)之外,一切都工作得很好。

我试过了:

.flight-img:nth-of-type(2n){
    float: right;
}

它似乎没有用。我尝试过:nth-​​child(2n)以及:nth-​​of-type / child(偶数)。

我确信我搞砸了一些事情,但不确定如何搜索我正在尝试做的事情以便找出答案。

编辑:添加

    $(document).ready(function(){
      $(".flight-img:even").css("float","right");
    });

完美地工作,我似乎无法使css :: pseudo类工作,并希望不使用jquery / js或尽可能少。

3 个答案:

答案 0 :(得分:1)

我认为问题在于您的明确div。 nth-of-type基于元素类型,而不是您使用的类选择器,因此明确的<div>计为.flight的兄弟姐妹和#flights {{1 }}。啊!我花了一分钟才弄明白,但4n-1应该适合你。虽然我应该提到还有其他方法来清除浮子。一种方法是在<div> overflow:hidden上使用.flight。这样你就可以通过取出明确的<div>来使用2n。

答案 1 :(得分:0)

您可以使用:odd伪选择器:

在你的css中:

.flight:nth-child(even) .flight-img {
    float:left;
}
.flight:nth-child(even) .flight-heading {
    float:right;
}

所以每个其他.flight容器中的flight-img和flight-heading将分别左/右浮动

希望有所帮助!

答案 2 :(得分:0)

也许我不太了解但是*选择器怎么样,比如:

<style>
.flight-img {
    background: yellow;/*put a img url*/
    background-size: cover;
    width: 40%;
    height: 400px;
    float: right;
}
.flight-heading {
    width: 60%;
    float: left;
    top: 50%;
}   
.flight-heading *{
    float: right;
}
</style>
<div class="flight">
  <div class="flight-img"></div>
  <div class="flight-heading">
    <h2>Shared Flights</h2>
    <p>The shared flight option is available for 1 to 5 people. This is our most economical   flight. You will fly with other passengers that are booked that day.</p>
    <button>Book Now</button>
  </div>
</div>