简体   繁体   English

如何在CSS中将绝对定位的项目居中

[英]How to center an absolutely positioned item in CSS

I've been looking around for answers to my problem, but i've mostly found answers to a problem that looks similar but remains different. 我一直在寻找问题的答案,但大多数情况下我都找到了看起来相似但仍然不同的问题的答案。

I have an image on which i am trying to place several other smaller images. 我正在尝试放置其他几个较小的图像的图像。 I placed the larger image in a so that i could use the "position:inherit" on my smaller images, and this works great : my images are perfectly well placed on their background. 我将较大的图像放在a中,以便可以在较小的图像上使用“ position:inherit”,而且效果很好:我的图像放置在背景上非常好。

My issue is that, in order to work, this requires my larger image to be styled as "position:absolute". 我的问题是,为了起作用,这要求将我的较大图像的样式设置为“ position:absolute”。 Hence, i'm unable to move my whole contraption to anywhere on the page but the top-left side where it currently resides. 因此,我无法将整个设备移动到页面上除当前位置所在的左上侧以外的任何位置。

HTML FILE : HTML文件:

<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="Map">

<img id="X0001Y0001" src="blue_brick.png">

</div>
</body>
</html>


CSS FILE : CSS文件:

#Map {
background-image:url('CoreMini.png');
height:128px;
width:256px;
position:absolute;
}

#X0001Y0001{position:inherit;top:0px; left:9px}

Wrap your #Map div in a parent div, and give the parent div the following: 将您的#Map div包裹在父div中,然后为父div #Map以下内容:

#parent {
  position: relative;
  margin: 0 auto;
  width: 256px;
}

See DEMO . 参见DEMO

Since your #Map is absolute then to position your image your need to use left and top . 由于#Mapabsolute因此要定位图像,您需要使用lefttop This will help you in positioning your images 这将帮助您定位图像

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM