如何使用 flexbox 使标题居中但导航一直向右?

问题描述 投票:0回答:3

我正在尝试使用 flexbox 并将

h1
nav
放在同一行,所以我有
display:flex
和默认的行方向。我希望标题居中,导航在右边。我想知道是否有办法将导航一直向右移动。我已经在
margin-right:auto
上尝试过
h1
并试图在设置为行时为主轴找到像
align-self
这样的属性,但我无法弄清楚。我本来有
justify-content:center
但放弃了并将其设置回
space-between
.

import React from 'react';
import { Link } from 'react-router-dom';

const Header = () => {
  return (
    <header className='header--container'>
      <Link to='/'>
        <h1 className='header--title'>Cocktail Connaisseur</h1>
      </Link>
      <Link to='/cocktails/a'>
        <nav className='header--nav'>
          <p>All Cocktails</p>
        </nav>
      </Link>
    </header>
  );
};

export default Header;

index.css

/*Header Styling */
.header--container {
  background-color: #55505c;
  padding: 15px;
  box-shadow: 0px 1px 5px rgba(0, 0, 0, 0.2);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header--container > a {
  text-decoration: none;
}

.header--title {
  margin: 0;
  color: #e8e9f3;
  font-size: 1.5em;
  text-align: center;
}

.header--nav {
  align-self: flex-end;
  margin-left: auto;
}

.header--nav > p {
  margin: 0;
  color: #e8e9f3;
}
html css flexbox styling
3个回答
1
投票

您可以在顶部再添加一个容器,然后您的输出将根据您的要求完美运行。

import React from 'react';
import { Link } from 'react-router-dom';

const Header = () => {
  return (
    <header className='header--container'>
      <div/>
      <Link to='/'>
        <h1 className='header--title'>Cocktail Connaisseur</h1>
      </Link>
      <Link to='/cocktails/a'>
        <nav className='header--nav'>
          <p>All Cocktails</p>
        </nav>
      </Link>
    </header>
  );
};

export default Header;

1
投票

添加弹性:1;到 .header--title 并且我从容器中删除了 justify

/*Header Styling */
.header--container {
  background-color: #55505c;
  padding: 15px;
  box-shadow: 0px 1px 5px rgba(0, 0, 0, 0.2);
  display: flex;
  
}

.header--container > a {
  text-decoration: none;
}

.header--title {
flex:1 ;
  margin: 0;
  color: #e8e9f3;
  font-size: 1.5em;
  text-align: center;
}

.header--nav {
  align-self: flex-end;
  margin-left: auto;
}

.header--nav > p {
  margin: 0;
  color: #e8e9f3;
}
<header class='header--container'>
      <Link to='/'>
        <h1 class='header--title'>Cocktail Connaisseur</h1>
      </Link>
      <Link to='/cocktails/a'>
        <nav class='header--nav'>
          <p>All Cocktails</p>
        </nav>
      </Link>
    </header>


1
投票

创建一个 div 并将标题放入 div:

<div class="header--title">
  <Link href="/">
    <h1>Cocktail Connaisseur</h1>
  </Link>
</div>

然后在CSS中:

.header--title {
  width: 80%; //You can modify this and see the exact amount due to responsive stuff.
  color: #e8e9f3;
  font-size: 1.5em;
  text-align: center;
  margin: 0;
  margin-left: 10%;
}

它会把你的标题放在中间,你的导航链接放在右边。

© www.soinside.com 2019 - 2024. All rights reserved.