使用CSS定位图像
我确实需要将图像放置在页面中的某个位置(例如,距左侧 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
没有任何项目总是从左上角放置。如果您知道图像的宽度,这应该很容易解释。
如果您的图像大小是动态的,那么最好使用 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.
[我假设图像宽度事先不知道,否则解决方案将是显而易见的]
我想你最好的选择是将其放入固定宽度的元素中并将其居中。当然,如果图像宽度不受限制并且可能超过容器元素宽度,则这会带来明显的缺点。
[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.
您知道图像的宽度还是有所不同?
如果您知道宽度,则可以设置位置,然后关闭边距。例如,如果您想将其居中于页面中间,则可以使用以下方法:
如果您的图像为 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:
if your image was 100x50px.
这是一个方法。将图像包装在
div
中,然后将 div 放置在您想要的位置,将其向左浮动,以便它折叠以适合其内容。然后margin-left: -50%
图像本身...演示
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. Thenmargin-left: -50%
the image itself...Demo