将一个元素置于导航中间

时间:2016-07-02 02:34:19

标签: html css centering

如何将导航设在顶部,根据图像的位置居中,而不是整个导航的块?

我之所以这么想是因为如果有人有一个很长的名字,那导航就不会看起来居中。我想知道如何建立一个相对位置,但我不确定这是否有用,或者使用花车或不是。



.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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

您可以设置第一个和最后一个<li>的绝对位置,以便它们不在正常的内容流中。然后只将中间<li>居中。对于对齐,您可以使用transform

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

&#13;
&#13;
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;
}
&#13;
<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>
&#13;
&#13;
&#13;

<强> jsFiddle

答案 1 :(得分:0)

.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我还写了一个快速片段。