html - CSS - 在不改变 HTML 的情况下将图像对齐到右上角和左上角

标签 html css layout

在长假(约 5 年)后,我开始从事网站 build 工作。 CSS 标准已经改变,我仍在努力跟上。

无论如何,我对 html 的质量仍然非常严格,不会在布局方面妥协。

这是我的 HTML。它不能改变,除了 image-rightimage-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)了我希望它在移动浏览器上的显示方式:一列包含标题、图像,然后是文本。

但是,在桌面浏览器上,我想让它看起来像这样(好吧,大概是这样):

enter image description here

不改变 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/

相关文章:

python - matplotlib 轴 ('tight' )不起作用?

android - 不使用 View.onDraw 和 canvas.setMatrix 缩放 subview

css - 构建可扩展/流动的 2 列矩形模块

javascript - 拖放列 PHP、JS,那怎么办?

css - Ruby on Rails 中的 Bootstrap CSS 路径

html - 为什么这个图像 sprite 菜单不能正确显示,为什么链接不起作用?

html - 如何使用 CSS 或 Multimarkdown 在新选项卡中打开超链接?

javascript - 提取漂亮网址的部分内容

jquery - 将 loader-div 添加到页面上的任何元素,同时模糊下面的内容

html - 溢出-y : Scroll not showing scrollbar