如何将文本与绝对定位的列表元素中心对齐?

时间:2017-11-05 17:43:22

标签: javascript html css css3

我有以下代码,



.testimonial-wrapper {
  background: green;
}

.testimonial {
  max-width: 980px;
  height: 70px;
  margin: auto;
  overflow: hidden;
  background: grey;
}

li {
  list-style: none;
  height: 70px;
}

.testimonial {
  position: relative;
}

li {
  position: absolute;
  top: 70px;
}

li.current{
  top: 0;
}

<div class="testimonial-wrapper">
    <div class="testimonial">
        <ul>
          <li class="current"><div>
            <p>This is the first test message</p>
            </div>  
          </li>
          <li>
            <div>
            <p>I have nothing more to say</p>
          </div></li>
          <li><div>
            <p>again if i could i would</p>
          </div>
          </li>
        </ul>
    </div>
  </div>
&#13;
&#13;
&#13;

我想将文本内容集中在推荐容器中。我试过p {text-align: center},但无济于事。我注意到当li没有绝对定位时,text-align: center起作用。

我缺少什么,我该如何纠正?

2 个答案:

答案 0 :(得分:2)

如果您只想在不使用flexbox的情况下使用当前解决方案将其居中,这应该有效,当元素绝对定位时,它将不再具有某些默认属性,例如width:100%才能生效。

希望它有所帮助!

.testimonial-wrapper {
  background: green;
}

.testimonial {
  max-width: 980px;
  height: 70px;
  margin: auto;
  overflow: hidden;
  background: grey;
}

li {
  list-style: none;
  height: 70px;
}

.testimonial {
  position: relative;
}

li {
  position: absolute;
  top: 70px;
  text-align: center;
  width: 100%;
}

li.current{
  top: 0;
}

ul {
  list-style: none;
  padding-left: 0;
}
<div class="testimonial-wrapper">
    <div class="testimonial">
        <ul>
          <li class="current"><div>
            <p>This is the first test message</p>
            </div>  
          </li>
          <li>
            <div>
            <p>I have nothing more to say</p>
          </div></li>
          <li><div>
            <p>again if i could i would</p>
          </div>
          </li>
        </ul>
    </div>
  </div>

答案 1 :(得分:2)

问题的原因是因为定位absolute

而没有占据整个宽度

所以,这是实现你想要的方式

&#13;
&#13;
.testimonial-wrapper {
  background: green;
}

.testimonial {
  max-width: 980px;
  height: 70px;
  margin: auto;
  overflow: hidden;
  background: grey;
  position: relative;
}

li {
  list-style: none;
  height: 70px;
}

.testimonial {
  position: relative;
}

li {
  position: absolute;
  left: 0;
  top: 70px;
  width: 100%;
  text-align: center;
}

li.current{
  top: 0;
}
&#13;
<div class="testimonial-wrapper">
    <div class="testimonial">
        <ul>
          <li class="current"><div>
            <p>This is the first test message</p>
            </div>  
          </li>
          <li>
            <div>
            <p>I have nothing more to say</p>
          </div></li>
          <li><div>
            <p>again if i could i would</p>
          </div>
          </li>
        </ul>
    </div>
  </div>
&#13;
&#13;
&#13;