CSS:使用flexbox简化HTML结构

时间:2017-11-12 10:54:47

标签: html css css3 flexbox

例如我有这个布局。它包括:

  • 左侧部分的图像。此图像将垂直居中
  • 右侧部分文字逐行显示。

enter image description here

我可以像这样结构html并使用一些布局,如Flexbox,div定位......

<div class="wrapper">
  <image class="avatar"></image>
  <div class="text">
    <div class="name">JameyJohnson</div>
    <div class="quote">I had little patience to begin with</div>
    <div class="date">6/10/2017</div>
  </div>
</div>

我想应用Flexbox,也只是这个html(没有对文本部分的包装)

<div class="wrapper">
  <image class="avatar"></image>
  <div class="name">JameyJohnson</div>
  <div class="quote">I had little patience to begin with</div>
  <div class="date">6/10/2017</div>
</div>

我可以将Flexbox用于上面的html结构吗?如果是,请告诉我如何。

1 个答案:

答案 0 :(得分:3)

为此你需要flex列,并且在wrapper上有一个固定的高度,这将限制文本的响应性(当文本可能换行时,wrapper将不会调整大小) 。

请注意,要使自定义元素正常工作,请在其类型名称前使用my-

Stack snippet

.wrapper {
  display: inline-flex;          /*  made it inline so it collapse to content width  */
  flex-flow: column wrap;
  justify-content: center;
  height: 70px;
}
my-image.avatar {
  background: url(http://placehold.it/30/f00) no-repeat left center;
  height: 100%;
  width: 50px;
}

/* sample with img */
.avatar {
  width: 30px;
  order: -1;                    /*  move before pseudo  */
}
.wrapper.nr2::before {          /*  a delimiter that break into a column of its own  */
  content: '';
  height: 70px;
  width: 20px;
}
<div class="wrapper">
  <my-image class="avatar"></my-image>
  <div class="name">JameyJohnson</div>
  <div class="quote">I had little patience to begin with</div>
  <div class="date">6/10/2017</div>
</div>

<div></div>

<div class="wrapper nr2">
  <img class="avatar" src="http://placehold.it/30/f00">
  <div class="name">JameyJohnson</div>
  <div class="quote">I had little patience to begin with</div>
  <div class="date">6/10/2017</div>
</div>

另一种选择是在background-image上使用wrapper,然后给它左边填充(所有这些都是用Flexbox完成的)。

Stack snippet

.wrapper {
  padding-left: 50px;
}
.avatar {
  background: url(http://placehold.it/30/f00) no-repeat left center;
}
<div class="wrapper avatar">
  <div class="name">JameyJohnson</div>
  <div class="quote">I had little patience to begin with</div>
  <div class="date">6/10/2017</div>
</div>

更新

如果有人需要在标记中设置图像源,那么在使用background-image时也可以这样做,就像这样,内联

Stack snippet

.wrapper {
  display: inline-flex;          /*  made it inline so it collapse to content width  */
  flex-flow: column wrap;
  justify-content: center;
  height: 70px;
}
my-image.avatar {
  background-position: left center;
  background-repeat: no-repeat;
  height: 100%;
  width: 50px;
}
<div class="wrapper">
  <my-image class="avatar" style="background-image: url(http://placehold.it/30/f00);"></my-image>
  <div class="name">JameyJohnson</div>
  <div class="quote">I had little patience to begin with</div>
  <div class="date">6/10/2017</div>
</div>

相关问题