将元素置于导航中间

Center an element in the middle of nav

如何使我的导航位于顶部,基于图像的位置居中,而不是整个导航的块?

我之所以想到这个是因为如果有人的名字很长,导航甚至不会看起来居中。我想知道是否要建立一个相对位置,但我不确定这是否可行,或者是否可以使用浮点数。

.profileinfo {
  padding: 0 10px;
  float: left;
}
.profileinfo:nth-child(2) img {
  align: middle;
  width: 60px;
  height: 60px;
  border-radius: 50%;
}
.profileinfo:first-child {
  border-right: 1px solid silver;
}
.profileinfo:last-child {
  border-left: 1px solid silver;
}
.profileinfo:last-child,
.profileinfo:first-child {
  margin-top: 20px;
}
#container {
  height: 80px;
  width: 300px;
  margin: 10px auto;
  padding: 0;
}
ul {
  list-style-type: none;
}
<ul id="container">
  <li class="profileinfo">Ashley Siwiec</li>
  <li class="profileinfo">
    <a href="/accounts/profile/">
      <img src="//dummyimage.com/60">
    </a>
  </li>
  <li class="profileinfo">C: 175</li>
</ul>

.profileinfo:nth-child(2) {
  background: #111;
}

.profileinfo:nth-child(2) img{
  width: 60px;
  height: 60px;
  border-radius: 50%;
}
.profileinfo:first-child {
  border-right: 1px solid white;
}
.profileinfo:last-child {

  border-left: 1px solid white;

}
.profileinfo:last-child, .profileinfo:first-child {
  margin-top:20px;
}
#container {
  display: flex;
  justify-content: center;
  align-items: center;
}
ul {
  list-style-type: none;
}
<ul id="container">
  <li class="profileinfo">Ashlefdsgsdfgfdsgdfsgy Siwiec</li>
  <li class="profileinfo">
    <a href="/accounts/profile/">
      <img src="/images/profilepics/github-512.png">
    </a>
  </li>
  <li class="profileinfo">C: 175</li>
</ul>

尝试使用 flexbox。这是一个解释它的有用网站:https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Using_CSS_flexible_boxes 我还写了一个简短的片段。

您可以为第一个和最后一个 <li> 设置绝对位置,这样它们就会脱离正常的内容流。然后只居中<li>。对于对齐,您可以使用 transform

这将确保中间图像始终水平居中。每边还有 2 个其他项目,垂直居中。

body {
  background: grey;
}

.container {
  position: relative;
  list-style-type: none;
  width: 300px;
  height: 60px;
  margin: 10px auto;
  padding: 0;
  text-align: center;
  color: white;
}

.container li {
  display: inline-block;
  padding: 0 10px;
}

.container li:nth-child(2) {
  width: 60px;
  height: 60px;
}

.container li:nth-child(2) img {
  border-radius: 50%;
}

.container li:first-child,
.container li:last-child {
  position: absolute;
  top: 50%;
}

.container li:first-child {
  border-right: 1px solid white;
  transform: translateX(-100%) translateY(-50%);
}

.container li:last-child {
  border-left: 1px solid white;
  transform: translateY(-50%);
}

.container li a {
  color: inherit;
}
<ul class="container">
  <li>Ashley Siwiec</li>
  <li><a href="/accounts/profile/"><img src="//dummyimage.com/60"></a></li>
  <li>C: 175</li>
</ul>

<ul class="container">
  <li>Ashleeeeey Siwieeeeec</li>
  <li><a href="/accounts/profile/"><img src="//dummyimage.com/60"></a></li>
  <li>C: 175</li>
</ul>

jsFiddle