CSS Flexbox 浮动元素

CSS Flexbox float elements(CSS Flexbox 浮动元素)

本文介绍了CSS Flexbox 浮动元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 flex 在图形"元素的右侧浮动两个元素,但它最终仅浮动 div1 在图形的右侧,并且 div2 被移动到下面,如果我使 div1 和 div2 足够窄,它们浮动在图的右侧.

I'm trying to float two elements at the right of a "figure" element using flex but it end up floating just div1 at the right of figure and div2 is moved bellow, if I make div1 and div2 narrow enough, they are floated inline at the right of figure.

这是 CSS:

.container {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
}

期望的结果:

实际结果:

推荐答案

它是如何工作的?

首先,您创建一个 flex-container(在这种情况下为 flexc) 并在其上应用 display:flex 属性,默认情况下以行对齐方式对齐元素.如果您希望元素保留其尺寸,请将其设置为 flex:0 0 auto; 否则您可以使用 flex:1; ,它会随着浏览器的运行而缩小或增长调整大小.

First, you make a flex-container (flexc in this case) and apply the display:flex property on it which aligns the elements by default in row alignment. If you want an element to preserve its dimensions set it to flex:0 0 auto; else you can make use of flex:1; which shrinks or grows as the browser is resized.

然后要对齐列(div1 和 div2)中的 内容,您可以将 then 包装在不同的容器中,因为 div 不是内联容器,并且flex 属性除了对 flex 父级的直接子级没有任何影响,它们以单独的行对齐.

Then to align the contents in column (div1 and div2) you can just wrap then in a different container and since div isn't an inline container, and the flex property doesn't have any effect on any other than the direct children of the flex parent, they are aligned in seperate lines.

.flexc {
  display: flex;
  justify-content: flex-start;
}

#fig {
  flex: 0 0 auto;
  width: 200px;
  height: 200px;
  background: gray;
  text-align: center;
  color: white;
  margin: 10px;
  border: 2px solid black;
}

#d1,
#d2 {
  width: 200px;
  height: 50px;
  background: purple;
  text-align: center;
  color: white;
  margin: 10px;
  border: 2px solid black;
}

<div class="flexc">
  <div id="fig">Figure</div>
  <div class="col">
    <div id="d1">div1</div>
    <div id="d2">div2</div>
  </div>
</div>

不改变html:

.flexc {
  display: flex;
  flex-direction:column;
  position:relative;
}

#fig {
  flex: 0 0 auto;
  width: 200px;
  height: 200px;
  background: gray;
  text-align: center;
  color: white;
  margin: 10px;
  border: 2px solid black;
}

#d1,
#d2 {
  position:absolute;
  left:250px;
  width: 200px;
  height: 50px;
  background: purple;
  text-align: center;
  color: white;
  margin: 10px;
  border: 2px solid black;
}
#d2{
top:70px;
}

<div class="flexc">
  <div id="fig">Figure</div>
    <div id="d1">div1</div>
    <div id="d2">div2</div>
</div>

这篇关于CSS Flexbox 浮动元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:CSS Flexbox 浮动元素

基础教程推荐