Hi so I was making a website and I just realized that it when I want to position the html element, it will position the element using the right side of it. Here's an example of what I mean. I was trying to position an image in the center using percentages. Trimmed down version of my css code: .image{position:absolute;right:50%;
So when I loaded the website, it shows up with the right corner of the picture at 50%, not the center of the image at 50%. Is there anyway to position using center of the image to position the picture at 50%, and not the left or right edge of the picture being at 50%? I don't want something like position:absolue;right:45%
to move the picture over, but instead use the center of the picture to position the picture. If you need any more clarification just let me know.
Asked
Active
Viewed 363 times
-1

Anish Sethi
- 11
- 3
-
Welcome to SO. Please try the search option before you submit a question. This has been already asked (and answered) many times. Thanks – Aziz Aug 14 '16 at 20:54
2 Answers
3
Set a width for the image and then set the left and right margins to auto.
` {width: whatever you want; margin-left: auto; margin-right: auto; } `

Orlando Morales-Cochran
- 84
- 10
-
-
Sorry, I should have been more clear. If you want to keep it as absolute position, set that first, then add left:0; right:0; then add what I mentioned above. – Orlando Morales-Cochran Aug 14 '16 at 20:46
-
Just tried it.. seems to work! Thanks! Heres the code I used: `.gold { background-image: url(../pics/emblems/Gold.jpg); width: 200px; left:0; right: 0; margin-left: auto; margin-right: auto; position: absolute; text-align: center; }` The question I have is, what the left:0 and right:0 do? – Anish Sethi Aug 14 '16 at 20:50
-
One last thing, so suppose I want to position some html text at right:25%. Would the same method work for using the center to position the element? – Anish Sethi Aug 14 '16 at 20:55
-
1
- You can do it easily using
text-align
, when element you want to position is inside some container, i.e:
HTML:
<div class="container">
<div class="image">Center me!</div>
</div>
CSS:
.container { text-align: center }
.image { display: inline-block }
- Second approach: if you know the width of the element (
.image
). Let's say that it is 400px wide:
CSS
.image {
position: absolute;
left: 50%;
margin-left: -200px;
}
A little bit tricky, can cause a problem when the width of the screen is lower than width of the element.

jedrzejginter
- 402
- 3
- 10
-
Thanks, but for the first one, I am using some text, so when I do text-align:center, it only centers the text relative to the image. Also, I forgot to mention but the image I am using is inserted using CSS `background-image:url(source)`. – Anish Sethi Aug 14 '16 at 20:46