css - 有没有办法在CSS中改变像素从右到左的流动而不是正常的从左到右

标签 css

例如,我们有一个始终位于页面右侧的元素(我们称它为接触框),我们希望一系列不同宽度的图像沿着它的左侧运行。每张图片的右手边缘应始终与接触框的左手边缘相距 20 像素。

如果我们知道接触框的宽度和位置,并且我们在图像上设置了 right 属性,那么它会从图像的左边缘而不是右边缘开始计算。这不会达到预期的结果,因为图像的宽度可变。

有没有办法在每个元素的基础上将此行为切换为从右向左流动,或者这是在 javascript 中理解它的唯一方法?

编辑:要清楚 - 图像的右边缘与 contact-box 容器元素的左边缘的左侧对齐 20px。图像宽度可变且响应迅速,接触框也是如此。

下图是元素可能如何定位的示例。

This is an example of the positioning of the elements

最佳答案

现在我想我明白了!使图像成为 contact-box 的子级。将 contact-box 设置为 position:relative,子图像设置为 position:absolute。现在将图像设置为 right:100% 并为其指定 20pxright-margin

<div class="contact-box">
  contact-box
  <img class="goLeft" src="http://placehold.it/350x150" />
</div>

在 CSS 中:

.contact-box {
  width: 200px;
  height: 200px;
  float: right;
  position: relative;
  background-color: #ccc;
}

.contact-box img.goLeft {
  position: absolute;
  right: 100%; /* aligns the right edge of the image to the left edge of the container*/
  margin-right: 20px; /* adds 20px spacing between the image and the container */
}

出于本次演示的目的,我将 contact-box 元素 float 到右侧,但它不需要 float 也能正常工作。

例子: https://jsfiddle.net/qvgknv4g/

* 替代解决方案 *

您还可以使用 CSS 的 direction 属性,并将其设置为 rtl(从右到左)。这将使用浏览器的自然渲染流程,并且图像是 contact-box 的兄弟:

<div class="outer">
  <div class="contact-box">
    contact-box
  </div>
  <img class="goLeft" src="http://placehold.it/180x150" />
</div>

还有 CSS:

.outer {
  direction: rtl;  /* This makes the magic happen */
  border: solid 1px #000;
}

.contact-box {
  width: 200px;
  height: 200px;
  background-color: #ccc;
  display: inline-block;
}

img {
  vertical-align: top; /* by default the image will render bottom-aligned to the text in conten-box.  This fixes that. */
  margin-right: 20px;
}

例子: https://jsfiddle.net/qvgknv4g/2/

关于css - 有没有办法在CSS中改变像素从右到左的流动而不是正常的从左到右,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30808657/

相关文章:

javascript - 固定位置 DIV 直到与其他元素发生碰撞

javascript - 防止拖动不可拖动元素时出现重影?

html - 无法显示背景图像

jquery - 如何更改表格中空单元格的背景颜色?

javascript - 如何限制 window.Open() 函数的窗口数

css - 将可变宽度的 div 定位在它的中点

css - 什么是右对齐子 div 并使父 div 从子 div 获取其宽度的跨浏览器兼容方式?

html - 应用 CSS 后在 Safari 中正确显示的输入框

css - 如何制作 Bootstrap 输入字段 "transparent"

javascript - 使用带自动完成功能的 YUI 布局