有没有办法在li之后用css显示div?

时间:2016-05-18 06:21:13

标签: html css printing tabs

我有以下标签结构:

<ul>
    <li id="first">First header</li>
    <li id="second">Second header</li>
    <li id="third">Third header</li>
    <li id="fourth">Fourth header</li>
</ul>
<div id="first_div">First content (related to first li)</div>
<div id="second_div">Second content (related to second li)</div>
<div id="third_div">Third content (related to third li)</div>
<div id="fourth_div">Fourth content (related to fourth li)</div>

在网页视图中,它会正确显示(使用一些简单的脚本:根据选定的li显示div)。

但是在打印视图中,这应该显示在以下结构中:

First header
First content

Second header
Second content

如果我在整个结构上添加display: block,它显然首先显示li s,然后显示div s。

有没有办法只用css形成所需的视图?

2 个答案:

答案 0 :(得分:2)

不,没有重复内容就不可能。但是,您可以按如下方式实现此目的:

<强> HTML:

<ul class="headers-list">
    <li class="first">First header</li>
    <li class="second">Second header</li>
    <li class="third">Third header</li>
    <li class="fourth">Fourth header</li>
</ul>

<div class="first print-header">First header</div>
<div id="first_div">First content (related to first li)</div>

<div class="second print-header">Second header</div>
<div id="second_div">Second content (related to second li)</div>

<div class="third print-header">Third header</div>
<div id="third_div">Third content (related to third li)</div>

<div class="fourth print-header">Fourth header</div>
<div id="fourth_div">Fourth content (related to fourth li)</div>

<强> CSS:

.print-header {
    display: none;
}

@media print {
    .headers-list {
        display: none;
    }
    .print-header {
        display: block;
    }
}

答案 1 :(得分:2)

如果要显示标题,则可以使用data-attributes

  

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes

/* @media print { */

ul {
  display:none;
  }

div:before {
  content:attr(data-title);
  display:block;
  font-size:1.4em;
  margin:1em 0 0.25em;
  background:gray;
  }

/*}*/
div {
  background:lightgray;
  }
<ul>
    <li id="first">First header</li>
    <li id="second">Second header</li>
    <li id="third">Third header</li>
    <li id="fourth">Fourth header</li>
</ul>
<div id="first_div" data-title="My First Header title">First content <br/>(related to first li)</div>
<div id="second_div" data-title="My Second Header title">Second content <br/>(related to second li)</div>
<div id="third_div" data-title="My Third Header title">Third content <br/>(related to third li)</div>
<div id="fourth_div" data-title="My Fourth Header title">Fourth content <br/>(related to fourth li)</div>