本文共 3007 字,大约阅读时间需要 10 分钟。
本文翻译自:
I'm having a problem centering an element that has the attribute position
set to absolute
. 我在将属性position
设置为absolute
的元素居中时遇到问题。 Does anyone know why the images are not centered? 有谁知道为什么图像没有居中?
body { text-align: center; } #slideshowWrapper { margin-top: 50px; text-align: center; } ul#slideshow { list-style: none; position: relative; margin: auto; } ul#slideshow li { position: absolute; } ul#slideshow li img { border: 1px solid #ccc; padding: 4px; height: 450px; }
参考:
A simple CSS trick, just add: 一个简单的CSS技巧,只需添加:
width: 100%;text-align: center;
This works on both images and text. 这适用于图像和文本。
Use margin-left: x%;
使用margin-left: x%;
where x is the half of the width of the element. 其中x是元素宽度的一半。
position: absolute;margin-left: auto;margin-right: auto;left: 0;right: 0;
Your images are not centered because your list items are not centered; 您的图像未居中,因为列表项未居中; only their text is centered. 只有他们的文字居中。 You can achieve the positioning you want by either centering the entire list or centering the images within the list. 您可以通过将整个列表居中或将列表中的图像居中来实现所需的定位。
A revised version of your code can be found at the bottom. 您的代码的修订版可以在底部找到。 In my revision I center both the list and the images within it. 在我的修订中,我同时将列表和其中的图像居中。
The truth is you cannot center an element that has a position set to absolute. 事实是,您不能将位置设置为绝对的元素居中。
Note: These instructions will work with any DOM block element, not just img. 注意:这些说明适用于任何DOM块元素,而不仅仅是img。
Surround your image with a div or other tag (in your case a li). 用div或其他标签(在您的情况下为li)包围图像。
Note: The names given to these elements are not special. 注意:这些元素的名称并不特殊。
Alter your css or scss to give the div absolute positioning and your image centered. 更改css或scss以使div绝对定位并使图像居中。
.absolute-div { position: absolute; width: 100%; // Range to be centered over. // If this element's parent is the body then 100% = the window's width // Note: You can apply additional top/bottom and left/right attributes // ie - top: 200px; left: 200px; // Test for desired positioning. } .absolute-div img { width: 500px; // Note: Setting a width is crucial for margin: auto to work. margin: 0 auto; }
Try this out: 试试看:
body { text-align : center; } #slideshow { list-style : none; width : 800px; // alter to taste margin : 50px auto 0; } #slideshow li { position : absolute; } #slideshow img { border : 1px solid #CCC; padding : 4px; height : 500px; width : auto; // This sets the width relative to your set height. // Setting a width is required for the margin auto attribute below. margin : 0 auto; }
I hope this was helpful. 我希望这可以帮到你。 Good luck! 祝好运!
Div vertically and horizontally aligned center Div垂直和水平对齐中心
top: 0;bottom: 0;margin: auto;position: absolute;left: 0;right: 0;
Note : Elements should have width and height to be set 注意:元素应设置宽度和高度
转载地址:http://dncnb.baihongyu.com/