gpt4 book ai didi

html - 如何在 CSS 中实现这种左右交替布局?

转载 作者:太空宇宙 更新时间:2023-11-04 12:02:32 32 4
gpt4 key购买 nike

我有一个网页,其中包含成排的新闻花絮以及相关的缩略图。

<div class="news-list">
<div class="news-item">
<div class="news-image">
<img class="news-image" src="penguin.jpg" />
</div>
<div class="news-info">
<p class="news-info">
Lorem ipsum dolor sit ... sapientem honestatis.
</p>
</div>
</div>

<div class="news-item">
<div class="news-image">
<img class="news-image" src="walrus.jpg" />
</div>
<div class="news-info">
<p class="news-info">
Mel et dolores luptatum ... dicta alienum.
</p>
</div>
</div>

<div class="news-item">
...
</div>

我目前通过 CSS 为页面设置了左侧所有图像和右侧描述的样式

div.news-list { display: table; }
div.news-item { display: table-row; }
div.news-image { display: table-cell; }
div.news-info { display: table-cell; }

但我想更改此布局以在左侧图片和右侧图片之间交替显示,如下面的模型所示:

Mockup of intended CSS layout

我在确定一个 CSS 解决方案来实现这种不需要我在实际标记中交替文本花絮和图像顺序的布局时遇到了麻烦。 (我很乐意根据需要将图像或文本放在第一位,但它应该在整个 HTML 中保持一致。)

有什么建议吗?

最佳答案

为了支持旧版浏览器,您可以添加偶数类和奇数类。

img.news-image {
background: #dadada;
height: 50px;
width: 50px;
}
p.news-info {
margin-top: 0;
}
.news-item {
clear: both;
border-top: 1px solid #dadada;
}
.odd div.news-info {
float: right;
}
.odd div.news-image {
float: left;
}
.even div.news-info {
float: left;
}
.even div.news-image {
float: right;
}
<div class="news-list">
<div class="news-item odd">
<div class="news-image">
<img class="news-image" src="penguin.jpg" />
</div>
<div class="news-info">
<p class="news-info">
Lorem ipsum dolor sit ... sapientem honestatis.
</p>
</div>
</div>

<div class="news-item even">
<div class="news-image">
<img class="news-image" src="walrus.jpg" />
</div>
<div class="news-info">
<p class="news-info">
Mel et dolores luptatum ... dicta alienum.
</p>
</div>
</div>
</div>

对于现代浏览器,您可以使用 css 伪类。

img.news-image {
background: #dadada;
height: 50px;
width: 50px;
}
p.news-info {
margin-top: 0;
}
.news-item {
clear: both;
border-top: 1px solid #dadada;
}
.news-item:nth-child(odd) div.news-info {
float: right;
}
.news-item:nth-child(odd) div.news-image {
float: left;
}
.news-item:nth-child(even) div.news-info {
float: left;
}
.news-item:nth-child(even) div.news-image {
float: right;
}
<div class="news-list">
<div class="news-item">
<div class="news-image">
<img class="news-image" src="penguin.jpg" />
</div>
<div class="news-info">
<p class="news-info">
Lorem ipsum dolor sit ... sapientem honestatis.
</p>
</div>
</div>

<div class="news-item">
<div class="news-image">
<img class="news-image" src="walrus.jpg" />
</div>
<div class="news-info">
<p class="news-info">
Mel et dolores luptatum ... dicta alienum.
</p>
</div>
</div>
</div>

关于html - 如何在 CSS 中实现这种左右交替布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29641664/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com