css中第一个可见的td和最后一个可见的td

时间:2018-05-21 07:02:31

标签: css

我试图在tr中设置第一个和最后一个可见的td。 我可以用上面的jquery来实现,但在我的情况下需要处理很多场景,测试需要时间。

经过大量的研究,我无法在CSS中获得任何东西。

是否有任何其他简单的黑客或解决方法,以便我只能用css实现。

以下几个选项,我试过

.visible {
display : block;
}

.hidden {
display : none;
}

td:first-child {
}

td:last-child {
}

td.visible:first-child {
}

td.visible:last-child {
}

4 个答案:

答案 0 :(得分:2)

  

css中没有向后移动,因此我们无法使用纯css选择tdcant



.hidden  {
  visibility: hidden;
}

.cant {
  background-color: orange!important;
}

tr td.hidden + td:not(.hidden) , tr td:not(.hidden):first-child { 
  background-color: red;
}

tr td.hidden + td:not(.hidden) ~ td , tr td:not(.hidden):first-child ~ td { 
  background-color: unset;
}

tr td:not(.hidden):last-child,tr td:not(.hidden):last-child {
  background-color: red!important;
}

<table border="1">
  <tr>
    <td class="hidden">This is TR1_TD1</td>
    <td>This is TR1_TD2</td>
    <td class="hidden">This is TR1_TD3</td>
    <td>This is TR1_TD4</td>
    <td>This is TR1_TD5</td>
  </tr>
 <tr>
    <td>This is TR2-TD1</td>
    <td class="hidden">This is TR2-TD2</td>
    <td class="hidden">This is TR2-TD3</td>
    <td class="cant">Can't with Pure Css</td>
    <td class="hidden">This is TR2-TD5</td>
  </tr>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

如果我告诉你的话,我说如果你的标记在浏览器执行时使用javascript是动态的,那么使用纯CSS无法实现这一点。

如果你可以控制它的生成过程,并且你的标记在服务器执行时是动态的(PHP,Java,等等......),你可以添加两个类,.first-visible和.last-visible给适当的元素和CSS中的样式。

CSS4添加了必要的功能来实现这一点,但它的支持仍未定义:https://css4-selectors.com/selector/css4/structural-pseudo-class/

你能添加普通的javascript而不是jQuery吗?

答案 2 :(得分:0)

我不完全确定这是否是你要求的,但是,这是我如何处理它的解决方案:

加载文档时,使用jQuery将类添加到要处理的所有元素中。

$(document).ready(function(){
   $("elements to select").addClass("selected"); // to all the elements you 
     want to handle
});

然后在css中使用该类编辑所选元素

.selected{
 // your code
}

答案 3 :(得分:0)

  

这个东西对你有用,我希望你会很高兴看到它。   您只能看到第一个TD和最后一个TD是可见的,否则隐藏。

table{
  border :1px solid #ddd;
}
//tr td{
//  display: none; // For Hide other TD
//}

tr td:first-child{
  color: darkgreen;
  display:block;
  background:lightgreen;
  padding:7px 15px;
  border-right:2px solid red;
}

tr td:last-child{
  color: skyblue;
  display:block;
  padding:7px 15px;
  background:blue;
  border-right:2px solid red;
}
<table>
  <tr>
   <td>This is first-child</td>
   <td>This is 2</td>
   <td>This is 3</td>
   <td>This is last-child</td>
  </tr>
  <tr>
   <td>one</td>
   <td>Two</td>
   <td>Three</td>
   <td>Four</td>
   <td>Five</td>
  </tr>
</table>

相关问题