首页 > 解决方案 > 不使用 CSS 浮动复制 html 定位

问题描述

我正在尝试使用此Grid 和 Flex Solution复制使用该属性对齐其内容的Float Example。我想在任何地方替换该属性,并且除了包含和框之外,我已经能够正确对齐所有东西。这是它应该看起来的样子: floatfloat<section><aside><div>使用浮点数对齐框

* {
  box-sizing: border-box;
  text-align: center;
}

section {
  padding: 20px;
  margin-bottom: 20px;
  background: #FFA500;
}

#full {
  width: 100%;
  overflow: auto;
  clear: both;
  color: #fff;
  background: #394549;
}

#division {
  padding: 20px;
  margin-top: 20px;
  background: #214fb3;
}

aside {
  float: left;
  width: 33%;
  height: 200px;
  padding: 20px;
  margin-left: 30px;
  background: #a6b747;
  border: 1px solid #eee;
}
 <section id="full">
    <aside>
      &lt;aside&gt; #a6b747
    </aside>
    &lt;section&gt; #394549
    <div id="division">
      &lt;div&gt; #6ea3da
    </div>
  </section>

这就是我目前position: absolute;<aside>盒子上使用的。 没有浮动的对齐框

* {
  text-align: center;
  font-size: 24px;
  line-height: 32px;
}

#full {
  grid-area: full;
  background: #394549;
  color: #fff;
  height: 200px;
  padding: 20px;  
}

aside {
  position: absolute;
  height: 160px;
  width: 33%;
  padding: 20px;
  margin-left: 30px;  
  background: #a6b747;
  border: 1px solid #eee;
}

#division {
  width: 100%;
  padding: 20px;
  background: #214fb3;
}
<section id="full">
  <aside>
    &lt;aside&gt; #a6b747
  </aside>
  &lt;section&gt; #394549
  <div id="division">
    &lt;div&gt; #6ea3da
  </div>
</section>

我不得不弄乱像素以以一种骇人听闻的方式获得正确的高度,但我不确定如何修复<div><aside>框的宽度。即使在调整窗口大小时,它们也应该与第一个示例保持一致,我也不知道如何对齐<section><div>文本。

标签: htmlcssflexboxgridcss-float

解决方案


因此,通过在侧面使用绝对定位,您需要在左侧为其余内容添加合适的填充,使其位于右侧空间的中心。

但是,因为您将 div 放在旁边,所以不能直接将大填充放在该部分上,否则它将把里面的所有东西推到右边。这意味着内容<section> #394549必须放在自己的容器中。我在新容器中添加了 margin-bottom 以将蓝色框向下推一点。

我添加到左侧的填充calc(33% + 64px);是为了说明左侧的边距,并在右侧的空间中很好地居中。

我还添加box-sizing: border-box;了所有内容,因为它使计算宽度更容易,并导致基于百分比的大小调整行为更明智。您可以改用content-box(默认),但您必须调整尺寸以适应帐户。您的原始尺寸正在使用border-box推理,因此我认为这是使您的尺寸表现得当的明智选择。

/* added box-sizing: border-box */
* {
  text-align: center;
  font-size: 24px;
  line-height: 32px;
  box-sizing: border-box;
}

#full {
  grid-area: full;
  background: #394549;
  color: #fff;
  height: 200px;
  padding: 20px;  
}

aside {
  position: absolute;
  height: 160px;
  width: 33%;
  padding: 20px;
  margin-left: 30px;  
  background: #a6b747;
  border: 1px solid #eee;
}

/* Added this container so we can put padding
   on content without effecting the blue box.
   also added margin-bottom to put a little
   space between this and the blue box */
#section-content {
  padding: 0 20px 0 calc(33% + 64px);
  margin-bottom: 10px;
}

/* added padding on the left */
#division {
  width: 100%;
  padding: 20px 20px 20px calc(33% + 64px);
  background: #214fb3;
}
<section id="full">
  <aside>
    &lt;aside&gt; #a6b747
  </aside>
  <!--added additional container #section-content-->
  <div id="section-content">
    &lt;section&gt; #394549
  </div>
  <div id="division">
    &lt;div&gt; #6ea3da
  </div>
</section>


推荐阅读