我遇到的问题是我有一个 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::伪类工作,并且希望不要为此或尽可能少地使用 jquery/js。
最佳答案
我认为问题是你清楚div
秒。 nth-of-type 基于元素类型,而不是你使用的类选择器,所以清楚 <div>
s算作.flight
的 sibling #flights
的 children <div>
.啊!我花了一分钟才弄明白,但 4n-1 应该适合你。尽管我应该提到还有其他方法可以清除 float 。一种方法是使用 overflow:hidden
在 .flight
上<div>
秒。这样你就可以通过取出清晰的 <div>
来使用 2n
关于html - 使 Div 开关 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26539477/