换行符的CSS选择器 [英] CSS selector for line breaks

查看:153
本文介绍了换行符的CSS选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有几个相邻的元素:

Suppose I have a few adjacent elements:

<div class="container">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
</div>

具有以下格式:

.container > div {
  display:inline-block;
  white-space:nowrap;
}

因为我们使用 display:inline-block div 将作为内联元素流动。我想要做的是能够指定应该应用当兄弟 div 被布置在同一行时应用的CSS规则

Since we're using display:inline-block, the divs will flow as inline elements. What I would like to do is to be able to specify a CSS rule that should be applied when sibling divs are laid out on the same line (i.e. there is no line break inserted inbetween).

例如,假设上面的 div 如下图所示:

As an example, let's assume that the divs above are laid out as in the following diagram:

[ 1 ][ 2 ][ 3 ][ 4 ]
[ 5 ][ 6 ] 



我想编写一个CSS规则, 4和6(即 div 与兄弟放在同一行)或逆集合(元素1和5,即 div

I would like to write a CSS rule that either matches elements 2, 3, 4 and 6 (i.e. divs with sibling(s) laid out on the same line) or the inverse set (elements 1 and 5, i.e. divs with no prior siblings laid out on the same line).

这对于样式非常有用,例如: (假设 ++ 是我正在寻找的选择器)

This would be really useful for styling, e.g. (supposing ++ is the selector I'm looking for)

.container > div ++ .container > div {
  /* separator between elements on the same line */
  border-right:1px solid #000; 
}


推荐答案

CSS,虽然它会有用。你可以通过检索定位数据,在JavaScript中检测它,例如它偏离文档的Y。当它不同时,您可以为其他样式添加类名。只需快速 jQuery 示例:

There is no such option in CSS, although it would be useful. You could detect it in javascript by retrieving positioningdata, like it's Y offset from the document. When it is different, you can add classnames for alternate styling. Just a quick jQuery example:

var topOffset;
$(document).ready(function(){
    $('.container div').each(function(index){
        if (index === 0) {
          // first item, set offset
          topOffset = $(this).offset().top;
          $(this).addClass('new-row');
        } else if (topOffset < $(this).offset().top){
          // new item, new row

          $(this).addClass('new-row');
          topOffset = $(this).offset().top;
        }
    });
});

这将导致:

<div class="container">
  <div class="new-row">1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div class="new-row">5</div>
  <div>6</div>
</div>

可以使用类选择器来适当地设置样式。

This can be styled appropiatly using the class selectors.

EDIT
jsFiddle上的工作示例

注意:在调整大小时不工作,但是当你将它移动到窗口调整大小调用的函数时可以修复。

Note: does not work on resize, but that can be fixed when you move it into a function that is called on window resize.

这篇关于换行符的CSS选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆