如何将“位置:绝对"居中元素 [英] How to center a "position: absolute" element

查看:19
本文介绍了如何将“位置:绝对"居中元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将属性 position 设置为 absolute 的元素居中时遇到问题.有谁知道为什么图像不居中?

body {文本对齐:居中;}#slideshowWrapper {边距顶部:50px;文本对齐:居中;}ul#幻灯片{列表样式:无;位置:相对;保证金:自动;}ul#slideshow li {位置:绝对;}ul#slideshow li img {边框:1px 实心 #ccc;填充:4px;高度:450px;}

<div id="slideshowWrapper"><ul id="幻灯片"><li><img src="https://source.unsplash.com/random/300*300?technology" alt="Dummy 1"/></li><li><img src="https://source.unsplash.com/random/301*301?technology" alt="Dummy 2"/></li>

解决方案

如果你已经设置了宽度,你可以使用:

位置:绝对;左边距:自动;右边距:自动;左:0;右:0;文本对齐:居中;

I'm having a problem centering an element that has the attribute position set to 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;
}

<body>
  <div id="slideshowWrapper">
    <ul id="slideshow">
      <li><img src="https://source.unsplash.com/random/300*300?technology" alt="Dummy 1" /></li>
      <li><img src="https://source.unsplash.com/random/301*301?technology" alt="Dummy 2" /></li>
    </ul>
  </div>
</body>

解决方案

If you have set a width you may use:

position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
text-align: center;

这篇关于如何将“位置:绝对"居中元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆