实现思路
- 使用媒体查询
@media
来判断屏幕宽度,针对不同宽度设置不同的布局。
- 对于图片和文字部分,在大屏幕下使用
flex
布局实现左右排列,小屏幕下使用默认的块级元素垂直排列。
- 通过
::before
或::after
伪元素添加文章发布日期,并使用position
定位来控制其位置。
关键CSS代码
/* 通用样式 */
.article {
display: flex;
flex-wrap: wrap;
align-items: flex-start;
}
.article img {
width: 100%;
height: auto;
}
.article p {
width: 100%;
}
/* 屏幕宽度大于800px时 */
@media (min-width: 801px) {
.article img {
width: 40%;
position: relative;
}
.article p {
width: 60%;
}
.article img::after {
content: "文章发布日期";
position: absolute;
top: 10px;
right: 10px;
background-color: rgba(0, 0, 0, 0.5);
color: white;
padding: 5px;
border-radius: 5px;
}
}
/* 屏幕宽度小于等于800px时 */
@media (max-width: 800px) {
.article img::after {
content: "文章发布日期";
display: block;
text-align: center;
background-color: rgba(0, 0, 0, 0.5);
color: white;
padding: 5px;
border-radius: 5px;
margin-top: 10px;
}
}
<div class="article">
<img src="article-image.jpg" alt="文章图片">
<p>文章文字内容...</p>
</div>