我试图在div中放置3个span元素。我有以下代码:



div {
  background-color: yellow;
  width: 400px;
  height: 30px;
}
#one {
  position: relative;
  font-weight: bold;
  left: 5%;
}
#two {
  position: relative;
  font-weight: bold;
  left: 40%;
}
#three {
  position: relative;
  left: 70%;
  font-weight: bold;
}

<div><span id="one">left</span><span id="two">middle</span><span id="three">right</span>
</div>





问题是,当您更改单词左,中和右时,位置会移动,因此它们不再居中。无论文本内容如何,​​如何将这些span元素居中?

最佳答案

div {
  background-color: yellow;
  width: 400px;
  height: 30px;
}
.inner {
   width: 33%;
   float: left;
   text-align: center;
}

<div><span id="one" class="inner">right</span><span id="two" class="inner">middle</span><span id="three" class="inner">left</span>
</div>





如果要覆盖1%的宽度(3 x 33%= 99%),可以执行以下操作:

.inner {
    float: left;
    text-align: center
}
.inner:not(:nth-of-type(2)) {
    width: 33%;
}
.inner:nth-of-type(2) {
    width: 34%;
}

关于html - 在div中放置3个span元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27618067/

10-09 23:14