CSS:垂直和水平对齐列表元素

CSS: align list element both vertically and horizontally

我的页眉有一个未对齐的 <li> 元素。这是屏幕截图:

基本上我想说"center both elements vertically, one to the left and the other to the right".

我可以对齐 <li> 元素

...但不是同时。基于 ,我希望它能工作:

style="float:right; vertical-align:middle"

没有。

我还找到了一些对齐整个列表的方法,但这些方法不适用于对齐列表中的单个元素。

这里是相关的 html-thymeleaf 代码:

    <div th:fragment="header">
        <nav>
            <ul class="navcontainer">
                <li class="navtitle"><a href="/"><h2>Personal Expense Tracker</h2></a></li>

                <li class="navlogout" th:inline="text" style="float:right"><a href="/logout">[[(${user != null ? 'Logout ' + user : ''})]]</a></li>

            </ul>
        </nav>
    </div>

这里是相关的css代码:

nav {
background-color: #333;
border: 1px solid #333;
color: #fff;
display: block;
margin: 0;
overflow: hidden;
}
nav ul{
margin: 0;
padding: 0;
list-style: none;
}
nav ul li {
margin: 0;
display: inline-block;
list-style-type: none;
transition: all 0.2s;
}
nav > ul > li > a {
color: #aaa;
display: block;
line-height: 2em;
padding: 0.5em 2em;
text-decoration: none;
}
nav > ul > li > a:hover {
background-color: #111;
}

使用您添加的代码..

使用 flexbox,你可以这样做:

nav {
  background-color: #333;
  border: 1px solid #333;
  color: #fff;
  display: block;
  margin: 0;
  overflow: hidden;
}

nav ul {
  margin: 0;
  padding: 0;
  list-style: none;
display: flex;/* added */
align-items: center;/* added */
justify-content: space-between;/* added */
}

nav ul li {
  margin: 0;
  display: inline-block;
  list-style-type: none;
  transition: all 0.2s;
}

nav > ul > li > a {
  color: #aaa;
  display: block;
  line-height: 2em;
  padding: 0.5em 2em;
  text-decoration: none;
}

nav > ul > li > a:hover {
  background-color: #111;
}
<div th:fragment="header">
  <nav>
    <ul class="navcontainer">
      <li class="navtitle"><a href="/"><h2>Personal Expense Tracker</h2></a></li>

      <li class="navlogout" th:inline="text" ><a href="/logout">Log out</a></li>

    </ul>
  </nav>
</div>


问题有点含糊。如果您可以让我了解您的问题/您正在寻找的结果,我可能会提供更多帮助。

无论如何,这是将元素与其父元素水平和垂直对齐的经典方法。

祝你好运!

.container {
  position: relative;
  display: block;
  margin: 0 auto;
  width: 50%;
  max-width: 1000px;
  height: 100px;
  background: grey;
}

.element {
  position: absolute;
  display: block;
  width: 50%;
  height: 50px;
  background: red;
  top: 50%;
  margin-top: -25px;
  left: 50%;
  margin-left: -25%;
}
<ul class="container">
  <li class="element"></li>
</ul>

你应该给元素 heightline-height(或者在某些情况下父元素没有高度)所以 vertical-align:middle 将不起作用,因为没有高度。 先给要设置垂直居中的元素设置高度,不行就给父元素设置高度。