问题
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.
回答1:
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; } `
回答2:
- 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.
来源:https://stackoverflow.com/questions/38946359/css-position-using-center-of-element-to-position-element-using-percentage