如何让我的元素正确对齐?

时间:2018-02-23 02:02:04

标签: html css angular twitter-bootstrap

我需要在我的角度应用中使用css帮助。

这是我的傻瓜: https://plnkr.co/edit/5GvpLHcGq93yfpqHAJwy?p=preview

但这里也是主要代码片段:

import {Component} from '@angular/core'

@Component({
  selector: 'app-child-component',
  template: `<div class="header">
  <div style="text-align:left;">
      <div class="headerText"> Foo 
        <div style="float:right;">
          <span class="headerText">Language</span>
          <span>
            <select style="margin-right:10px;margin-top:4px;">
              <option *ngFor="let language of languages">{{language}}</option>
            </select>
          </span>
        </div>
      </div>
      <div class="headerText"> Bar
          <div style="text-align:-webkit-right; padding-right:10px;">
            <span class="headerText">
              user: admin
            </span>
          </div>
      </div>
  </div>
  <div style="float:right;">
    <div>
      <button class="signOutButton">Sign Out</button>
    </div>
  </div>
</div>



  `,
  styles: [`.signOutButton {
    background:#5dacb4 !important;
     width:100px;
     height:30px;
     font-size:14px;
     margin:5px;
     float:right;
 }

 .header {
      background:#3f3f3f;
  }

  .headerText {
      color:#ffffff;
      font-size:16px;
      margin-bottom:0px;
      margin-left:10px;
  }`]
})
export class ChildComponent {}

我遇到的问题是我需要user:adminBar位于同一行 并sign out按钮在languageuser之后一直对齐,并在右侧居中垂直对齐。

我怎样才能实现这一目标?

1 个答案:

答案 0 :(得分:1)

有点像这样吗?

.signOutButton {
  background:#5dacb4 !important;
  width:100px;
  height:30px;
  font-size:14px;
  position:absolute;
  right:10px;
  top:50%;
  transform:translateY(-50%);
}

.header {
  background:#3f3f3f;
  color:#ffffff;
  font-size:16px;
  position:relative;
  padding:10px;
}

.left {
  float:left;
}

.right {
  float:right;
}

.line {
  width:calc(100% - 110px);
}
.line::after { /* CLEARFIX */
  content: "";
  clear: both;
  display: table;
}
<div class="header">

  <div class="line">
    <div class="left">
      Foo
    </div>
    <div class="right">
      <select>
        <option>English</option>
      </select>
    </div>
  </div>
 
   <div class="line">
    <div class="left">
      Bar
    </div>
    <div class="right">
      user:admin
    </div>
  </div>
 
  <button class="signOutButton">Sign Out</button>
</div>

基本上,通过这样的设计,我采用的方法是将其分为两部分:两条“Foo”/“Bar”线和Sign Out按钮。

每条线都需要有一些东西与它左边对齐,并且某些东西与它对齐。正常的文本行不能这样做,但它是使用float的完美场景!

不幸的是,浮动元素不占用任何空间,并且由于这些行完全由浮动元素组成,这意味着它们本身不占用任何空间。值得庆幸的是,这个问题很久以前就得到了解决,通常称为clearfix hack。这就是我们在这里使用的。

对于“注销”按钮,我们需要在正确的位置弹出一点绝对定位(请记住,使用relativeabsolute定位的元素内的绝对定位元素将相对定位到那个元素,而不是整个页面)。但是,线条将与按钮重叠。不好。

因此,我们只需要使线条略短。多短了多少?我会说110px,因为按钮是100px,如果我们在行尾和按钮之间留出10px空格,而不是按下它们,它会看起来更好相互对立。我们可以使用calc()将这些行完全 110px缩短,只需将此值减去100%

相关问题