水平对齐 CSS HTML 的问题

时间:2021-03-31 19:12:20

标签: html css

我需要以水平格式放置链接。你能帮我做吗?

这是代码(HTML):

<body>
    <header>
        <h1>Site Name</h1>
        <a href=#>About</a>
        <a href=#>Services</a>
        <a href=#>Contact</a>
    </header>
</body>

这是代码(CSS):

header {
    width: 100%;
    background-color: red;
}
h1 {
    font-size: inherit;
}
a {  
    margin:auto;
    margin-left: 70%;
    display:block;
}

2 个答案:

答案 0 :(得分:1)

  1. 将 flexbox 应用到容器:header { display: flex; }

  2. 通过简单地将项目垂直居中对齐它们:header { align-items: center; };

  3. 通过给第一个锚点一个 auto 的左边距将链接对齐到右侧:header a:first-of-type { margin-left: auto; }

header {
  width: 100%;
  background-color: red;
  display: flex;
  align-items: center;
}

h1 {
  font-size: inherit;
}

header a {
  margin: 0 0.5em;
  display: block;
}

header a:first-of-type {
  margin-left: auto;
}
<body>
  <header>
    <h1>Site Name</h1>
    <a href=#>About</a>
    <a href=#>Services</a>
    <a href=#>Contact</a>
  </header>
</body>

答案 1 :(得分:-2)

请试试这个并告诉我它是否对你有好处;-)

body {
  margin: auto;
  font-family: 'Avenir LT W01 35 Light', sans-serif;
  display: flex;
  flex-direction: column;
  background-repeat: no-repeat;
  background-size: cover;
}

header {
  width: 100%;
  background-color: red;
}

h1 {
  font-size: inherit;
}

a {
  margin: auto;
  margin-left: 70%;
  display: block;
}
<body>
  <header>
    <h1>Site Name</h1>
    <a href=#>About</a>
    <a href=#>Services</a>
    <a href=#>Contact</a>
  </header>
</body>