如何浮动到块级元素的右侧,并与块级元素齐平

时间:2018-03-10 09:16:42

标签: css css-position

我想要一个看起来像这样的网页......



header {
  border-style: solid;
  border-top-width: 5px;
  background-color: red;
}

p {
  background-color: yellow;
}

header #btnLogIn {
  float: right;
  position: absolute;
  right: 170px;
  top: 40px;
}

header #btnGoogleLogIn {
  float: right;
  position: absolute;
  right: 30px;
  top: 40px;
}

<header>
  <h1>Site Title</h1>
  <button id="btnLogIn" type="button">Log in</button>
  <button id="btnGoogleLogIn" type="button">Log in with Google</button>
</header>
<hr/>
<p>Some text</p>
&#13;
&#13;
&#13;

按钮需要与h1标题位于同一水平面上,向右浮动,两者之间有一些很好的边距。按钮标题可以动态更改(通过语言选择),因此任何具有硬编码right属性值的解决方案都会失败。

如何使按钮以与h1元素相同的行向右浮动,其方式与按钮宽度无关?解决方案需要是css。

3 个答案:

答案 0 :(得分:1)

像这样使用flexbox:

&#13;
&#13;
$(window).load(function(){
 (function() { 
      someProcess = function(vid){...}
      result = someProcess(document.getElementById('video'));
  })();
});
&#13;
header {
  border-style: solid;
  border-top-width: 5px;
  background-color: red;
  display: flex;
  align-items: center;
}

p {
  background-color: yellow;
}

header button {
  margin: 0 10px;
}

header h1 {
  margin-right: auto;
}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

Flexbox就是答案:

<强> HTML:

<header>
  <div class="header-left">
    <h1>Site Title</h1>
  </div>
  <div class="header-right">
    <button class="btn" type="button">Log in</button>
    <button class="btn" type="button">Log in with Google</button>
  </div>
</header>
<hr/>
<p>Some text</p>

<强> CSS:

header {
  border-style: solid;
  border-top-width: 5px;
  background-color: red;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

header .btn {
  margin: 0 10px;
}

p {
  background-color: yellow;
}

答案 2 :(得分:1)

这对你有用吗?

header {
  border-style: solid;
  border-top-width: 5px;
  background-color: red;
  display: flex;
  align-items: center;
}
header h1 {
  flex: 1;
}

header button {
  margin: 0 1em;
}
p {
  background-color: yellow;
}
<header>
  <h1>Site Title</h1>
  <button id="btnLogIn" type="button">Log in</button>
  <button id="btnGoogleLogIn" type="button">Log in with Google</button>
</header>
<hr/>
<p>Some text</p>