在长假(约 5 年)后,我开始从事网站 build 工作。 CSS 标准已经改变,我仍在努力跟上。
无论如何,我对 html 的质量仍然非常严格,不会在布局方面妥协。
这是我的 HTML。它不能改变,除了 image-right
和 image-left
类。这些可以用相应图像上的 class="right
"或 class="left
"替换。
<div class="text-block image-left">
<h2>A block of text with image on the left</h2>
<img src="https://picsum.photos/300/200" alt="A nice picture" />
<p>
This is one paragraph.
</p>
<p>
This is the second paragraph.
</p>
</div>
<div class="text-block image-right">
<h2>A block of text with image on the right</h2>
<img src="https://picsum.photos/300/200" alt="A nice picture" />
<p>
This is one paragraph.
</p>
<p>
This is the second paragraph.
</p>
</div>
上面的 HTML 反射(reflect)了我希望它在移动浏览器上的显示方式:一列包含标题、图像,然后是文本。
但是,在桌面浏览器上,我想让它看起来像这样(好吧,大概是这样):
在不改变 HTML 的情况下实现该布局并具有响应式布局的合适 CSS 是什么?
最佳答案
CSS Grid 很棒,但为此你最好的选择是使用 Flexbox,并且使用一些语义化的 HTML5 也会对可访问性有好处。
对于您的 HTML:
<figure class="image-left">
<img src="https://picsum.photos/300/200" alt="A nice picture" />
<figcaption>
<h2>A block of text with image on the left</h2>
<p>This is one paragraph.</p>
<p>This is the second paragraph.</p>
</figcaption>
</figure>
<figure class="image-right">
<img src="https://picsum.photos/300/200" alt="A nice picture" />
<figcaption>
<h2>A block of text with image on the right</h2>
<p>This is one paragraph.</p>
<p>This is the second paragraph.</p>
</figcaption>
</figure>
对于你的 CSS:
/* Add styling here you wish to add for screens with a width less than 600px */
@media screen and (min-width: 600px) {
/* Add styling here you wish to add for screens with a width of 600px and wider */
figure {
display: flex;
}
figcaption {
width: 100%;
}
.image-left {
flex-direction: row-reverse;
}
.image-right {
/* This is set to flex-direction: row; by default so doesn't need to be added */
}
}
如有任何问题或需要额外帮助,请随时在下方评论:)
关于html - CSS - 在不改变 HTML 的情况下将图像对齐到右上角和左上角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57543469/