简体   繁体   English

页内响应式CSS?

[英]In-page responsive CSS?

I'm trying to figure out if there's a way using only HTML and CSS to build elements within a page that are responsive to the other elements, rather than to the browser size as is with @media and traditional responsive design. 我试图弄清楚是否有一种方法只使用HTML和CSS在页面中构建响应其他元素的元素,而不是像@media和传统的响应式设计那样的浏览器大小。

For example, I have an element that is 900px wide. 例如,我有一个900px宽的元素。 It can sometimes contain 1, 2 or 3 child elements. 它有时可以包含1,2或3个子元素。 I want the child elements to style and display additional elements depending on how many sibling elements there are. 我希望子元素可以根据有多少兄弟元素来设置样式并显示其他元素。

Eg 例如

<div id="parent">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
</div>

vs VS

<div id="parent">
    <div class="child"></div>
    <div class="child"></div>
</div>

The child elements would appear differently - different widths, different padding, borders... and they would also have child elements which would be hidden in the first sample, but display in the second. 子元素将以不同的方式显示 - 不同的宽度,不同的填充,边框......并且它们还具有将隐藏在第一个样本中的子元素,但显示在第二个样本中。

I know this can be done with JS, PHP... but I'm trying to see if there's a way to do it without it. 我知道这可以用JS,PHP来完成......但是我试着看看有没有办法在没有它的情况下做到这一点。 Since I also want to hide/show specific elements depending on the existence of other child elements, using relative sizes (eg %) doesn't cut it. 由于我还想根据其他子元素的存在隐藏/显示特定元素,因此使用相对大小(例如%)不会削减它。

Thanks 谢谢

It's possible with CSS3 , it took me a couple of minutes to figure it out. 这可能与CSS3 ,我花了几分钟来弄明白。

Check out http://jsfiddle.net/Vdz7s/ . 查看http://jsfiddle.net/Vdz7s/

HTML: HTML:

<h1>One:</h1>
<div class="parent">
    <div class="child">1</div>
</div>

<h1>Two:</h1>
<div class="parent">
    <div class="child">1</div>
    <div class="child">2</div>
</div>

<h1>Three:</h1>
<div class="parent">
    <div class="child">1</div>
    <div class="child">2</div>
    <div class="child">3</div>
</div>​

CSS: CSS:

.parent .child:nth-last-child(1)
{
    border:1px solid yellow;
}

.parent .child:nth-last-child(2),
.parent .child:nth-last-child(2) ~ .child
{
    border:1px solid orange;
}

.parent .child:nth-last-child(3),
.parent .child:nth-last-child(3) ~ .child
{
    border:1px solid red;
}
​

I think that the code is pretty self-explanatory, then you just need to target the children childs and do whatever you want with them. 我认为代码是非常明显的,然后你只需要针对孩子们的孩子,并用他们做任何你想做的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM