首页 > 解决方案 > 变换时的元素宽度: translate()

问题描述

我将 ul 列表(但可以是任何元素)绝对定位在容器的底部中心。当窗口或容器被调整大小时,列表会缩小,就好像它是某种应用的边距或填充或最大宽度。看到这个小提琴

想要的效果 我需要列表保持一个自动宽度(取决于它的内容),并且只有当它超过父宽度的 100% 时才会缩小。

我注意到这种行为仅在 transform: translateX(-50%) 时发生。

编辑 包装器 div 包含其他元素。列表充当导航菜单或工具箱。

HTML

<div id="wrapper">

  <p>Whatever other content</p>

  <ul id="list">
    <li><span></span></li>
    <li><span></span></li>
    <li><span></span></li>
    <li><span></span></li>
    <li><span></span></li>
  </ul>
</div>

CSS

* {
  margin: 0;
  padding: 0;
}

html,
body {
  height: 100%;
}

#wrapper {
  position: relative;
  height: 100%;
  width: 100%;
  background: #fff;
}

#list {
  list-style: none;
  position: absolute;
  padding: 2px;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  font-size: 0;
  background: #555;
}

#list li {
  display: inline-block;
  margin: 1px;
}

#list span {
  display: block;
  height: 40px;
  width: 40px;
  background: #222;
}

标签: htmlcsscss-transforms

解决方案


您可以使用 flexbox 替换旧的绝对定位方式。

#wrapper {
  background: #fff;
  height: 100%;
  width: 100%;
  position: relative;
  display: flex;
}
#list {
  margin: 0;
  padding: 0;
  list-style: none;
  align-self: flex-end;
  margin: 0 auto;
  border: 1px solid #222;
}

我更新了小提琴http://jsfiddle.net/uLj5raoq/


推荐阅读