使用CSS定位图像

发布于 2024-08-30 05:36:29 字数 143 浏览 3 评论 0原文

我确实需要将图像放置在页面中的某个位置(例如,距左侧 100 像素),但我想控制图像的中心位置, 当我使用 left:100px; ,图像的位置距其左边缘 100px,而不是距中心 100px...

有没有办法我可以选择图像的中心位置,而不是左/右边缘?

i really need to place an image somewhere in the page (100 pixels from the left side for example) but i want to control where the center of the image will be,
when i use left:100px; , the image is positioned 100px from its left edge and not from its center...

is there a way i can choose where the center of the image will be and not the left/right edge?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

淡笑忘祈一世凡恋 2024-09-06 05:36:29

没有任何项目总是从左上角放置。如果您知道图像的宽度,这应该很容易解释。

如果您的图像大小是动态的,那么最好使用 Javascript 进行此类定位。

No items are always placed from their top-left corner. If you know the width of the image, this should be easy to account for.

If your image size is dynamic, it may be best to do this type of positioning using Javascript.

魂牵梦绕锁你心扉 2024-09-06 05:36:29

[我假设图像宽度事先不知道,否则解决方案将是显而易见的]

我想你最好的选择是将其放入固定宽度的元素中并将其居中。当然,如果图像宽度不受限制并且可能超过容器元素宽度,则这会带来明显的缺点。

[I'm assuming image width is not know in advance, otherwise solution would be obvious]

I guess your best option is to put it in an element with fixed width and center it inside that. Of course, this has obvious drawbacks if image width is unlimited and can exceed container element width.

苍风燃霜 2024-09-06 05:36:29

您知道图像的宽度还是有所不同?

如果您知道宽度,则可以设置位置,然后关闭边距。例如,如果您想将其居中于页面中间,则可以使用以下方法:

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  margin-top: -50px;
  margin-left: -100px;
}

如果您的图像为 100x50px。

Do you know the width of the image or does it vary?

If you know the width, you can set the position and then back the margin off. For example, if you wanted to center it in the middle of the page you could use this:

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  margin-top: -50px;
  margin-left: -100px;
}

if your image was 100x50px.

半枫 2024-09-06 05:36:29

这是一个方法。将图像包装在 div 中,然后将 div 放置在您想要的位置,将其向左浮动,以便它折叠以适合其内容。然后 margin-left: -50% 图像本身...

  <div style="position: relative; left: 300px; border: 1px solid red; float: left">
      <img src="#" style="position: relative; margin-left: -50%"/>
  </div>

演示

Here's an approach. You wrap the image in a div, and then position the div where you want it, float it left so that it collapses to fit it's contents. Then margin-left: -50% the image itself...

  <div style="position: relative; left: 300px; border: 1px solid red; float: left">
      <img src="#" style="position: relative; margin-left: -50%"/>
  </div>

Demo

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文