html - 将元素移动到右边距而不使用 CSS 从 HTML 流中移除

标签 html css position

我在页面居中有一列固定宽度。由于视口(viewport)不同,边距是未知的。我想将它移到屏幕的左边缘而不将其从 HTML 流中移除。

<main class="centered" style="width:750px;margin-left:auto;margin-right:auto">
...
  <figure class="imagefullwidth" style="width:100vw">
    <img src="image.jpg">
  </figure>
...
</main>

应该是这样的:

       _______main_______
      |                 |
      |                 |
 _____|______figure_____|_____     
|                             |
|                             |     
|                             |     
|_____________________________|     
      |                 |
      |                 |
      |                 |
      |_________________|

当然,我试过了position: absolute; left: 0<figure>但这使它脱离了 HTML 流程。我试过 position: absolute;在图像上,虽然我可以创建比其容器更大的图像,left:0只将图像放在 <main> 的左边缘(加上允许 <figure> 折叠到高度 0,我不知道图像的高度来给它一个高度)。

负边距没有帮助,因为我不知道任何特定视口(viewport)宽度的边距宽度。 float: left不起作用,因为它漂浮在容器内。

我无法修改 HTML,因为它来自 CMS。但是有很多 wrapper 和我可以设计的东西。

你能想出一种不用 JS 的纯 CSS 来做到这一点的方法吗?

Attempting to make the image larger than its container - left:0 can't break out of main container

最佳答案

基于提供的 html 和可视示例,下面的 CSS 似乎可以完成您所追求的。 JSFiddle example

.centered {
  background-color: gray;
  width: 100% !important;
  max-width: 750px;
}

.imagefullwidth {
  width: initial !important;
}

.imagefullwidth img {
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  width: 100vw;
  height: auto !important;
}

关于html - 将元素移动到右边距而不使用 CSS 从 HTML 流中移除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58776686/

相关文章:

javascript - 如何使滚动条长度小于父 block ?

html - 水平展开div不溢出 :hidden

html - CSS div 超出页面限制,添加水平滚动条

javascript - CSS 渲染不正确;可能链接的 JS/CSS 资源过多?

html - Li 在 float 的 div 之上

JavaScript按钮onclick不起作用

jquery - 如何向动态创建的图像添加边框图像?

jquery 单击 flash 对象内的一个位置

jquery - 无法在移动 Safari 上单击固定位置元素

html - 获取加载的 UIWebView 的 HTML 源代码