如何用CSS划分内容,奇怪?

时间:2016-11-14 05:09:27

标签: html css

我有一个包含这样内容的页面。

#################################
#  __________________________   #
# |           |              |  #
# |          |               |  #
# |  text   |       IMAGE    |  #
# |        |                 |  #
# |_______|__________________|  #
#                               #
#  __________________________   #
# |           |              |  #
# |          |               |  #
# |  IMAGE  |        text    |  #
# |        |                 |  #
# |_______|__________________|  #
#################################

我的代码如下:

<!-- <p> -> <image> -->
<div class="even_odd">
    <p></p>
</div>
<div class="even_odd">
    <img src="" alt="">
</div>

<!-- <image> -> p -->
<div class="even_odd">
    <img src="" alt="">
</div>
<div class="even_odd">
    <p></p>
</div>

现在,我想设置默认的CSS:

当号码为odd时,会将text设置为float: left,将image设置为float: right

当号码为even时,会将image设置为float: left,将text设置为float: right

目前,我必须这样做:

.even_odd:nth-child(1), event_odd:nth-child(4), ..... many and many child .... {
   float: left;
}

.even_odd:nth-child(2), event_odd:nth-child(3), ..... many and many child .... {
   float: left;
}

3 个答案:

答案 0 :(得分:5)

我们尝试这个CSS选择器。

selector:nth-child(odd) {
    property
}

selector:nth-child(even) {
    property
}

答案 1 :(得分:1)

我从OP的请求中收集到的是img / div块的交替布局。以下是代码段的概述:

  • main.main是一切都在其中的容器。
    • 这是一个列灵活容器。
  • 有3 section.row
    • 它们是main.main的弹性项目,也是弹性容器。
    • 默认情况下,每个奇数有序的部分都是flex-direction:row
    • 每个偶数部分都是flex-direction:row-reverse
  • 每个img.img都有div.txtsection.row
    • 每一对居住在偶数section.row的人都是颠倒了。

注意:关于nth选择器需要记住的重要事项是:

  • 它们适用于元素在其兄弟姐妹和祖先中的位置。
  • 替代nth-of-type将过滤掉与选择器中的标记不匹配的其他兄弟。
    • 例如,如果有一个div和section的混合,并且选择器是:div:nth-of-type(even) {color:red;}每个偶数的div都是红色的,无论有多少个部分。
    • 如果您在前面提到的情况下使用了div:nth-child(even) {color:red},结果仍会使div变为红色,但也会对这些部分进行计数(但不会应用红色文本颜色)。
    • 他们不识别类或任何属性选择器。
顺便说一下,尽量避免float它们是脆弱的遗物,了解flexbox它是你的朋友。

.main {
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  width: 100px;
  padding: 0 5px;
  height: auto;
  background: grey;
}
section:nth-of-type(odd) {
  display: flex;
}
section:nth-of-type(even) {
  display: flex;
  flex-direction: row-reverse;
}
.txt {
  width: 50px;
  height: 50px;
}
<main class="main">
  <section class='row'>
    <img src='http://placehold.it/50x50/000/fff?text=1' class='img'>
    <div class='txt'>TEXT</div>
  </section>
  <section class='row'>
    <img src='http://placehold.it/50x50/00f/eee?text=2' class='img'>
    <div class='txt'>TEXT</div>
  </section>
  <section class='row'>
    <img src='http://placehold.it/50x50/0e0/111?text=3' class='img'>
    <div class='txt'>TEXT</div>
  </section>
</main>

答案 2 :(得分:0)

试一试: -

tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}