CSS Flexbox浮动元素 [英] CSS Flexbox float elements

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

问题描述

我正在尝试使用flex在"figure"元素的右边浮动两个元素,但最终仅在图的右边浮动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 in this case)并在其上应用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.

然后对齐contents in column (div1 and div2),您可以将其包装然后放在另一个容器中,并且由于div isn't an inline container,并且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浮动元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆