【问题标题】:How to make an HTML element sit to the left of parent container?如何使 HTML 元素位于父容器的左侧?
【发布时间】:2019-12-24 04:22:45
【问题描述】:

在我的 Angular 应用程序中,我有一个 HTML 父级,其中包含这样的子项:

<div class="parent">
    <div class="child1"></div>
    <div class="child2"></div>
    <div class="child3"></div>
</div>

我希望 child2child3 位于 parent 内部,左对齐。但我希望child1 位于parent 的左侧。我知道一种解决方案是在parent 之前声明child1,但我希望child1 仍然在parent 中声明。我也不想使用 Javascript 来查找 child1 的宽度并用它来抵消它;我只想使用 CSS。

关于如何解决这个问题的任何想法?

【问题讨论】:

  • 一些视觉效果会有所帮助,并且您拥有的当前 css

标签: html css angular


【解决方案1】:

未知宽度的孩子唯一实用的方法是绝对定位。

.parent {
  width: 50%;
  margin: 1em auto;
  border: 1px solid red;
  position: relative;
  display: flex;
}

.parent div {
  border: 1px solid green;
  white-space: nowrap;
  padding: .25em;
}

.child1 {
  position: absolute;
  top: 0;
  right: 100%;
}
<div class="parent">
  <div class="child1">Child 1</div>
  <div class="child2">Child 2</div>
  <div class="child3">Child 3</div>
</div>

【讨论】:

    【解决方案2】:

    如果您不想使用 flexbox,请尝试这样的操作:

        *{
     box-sizing: border-box;
    }
    .parent{
      width:200px;
      height:100px;
      margin-left:200px;
      box-sizing: border-box;
      border:3px solid red; 
      position:relative;
    }
    .child1 {
      width:100px;
      height:100%;
      border:1px solid blue;
      box-sizing: border-box;
      position:absolute;
      left:-100px;
    }
    
    .child2 {
      width:50%;
      height:100%;
      background:blue;
      float:left;
    }
    
    .child3 {
      width:50%;
      height:100%;
      background:orange;
      float:left;
    }
    <div class="parent">
      <div class="child1">Child 1</div>
      <div class="child2">Child 2</div>
      <div class="child3">Child 3</div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-06
      • 1970-01-01
      • 2015-01-22
      • 1970-01-01
      • 1970-01-01
      • 2014-10-26
      • 2016-03-21
      • 2021-04-09
      相关资源
      最近更新 更多