gpt4 book ai didi

html - CSS:使用 flexbox 简化 HTML 结构

转载 作者:太空宇宙 更新时间:2023-11-03 22:34:12 25 4
gpt4 key购买 nike

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

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

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 结构吗?如果是,请告诉我怎么做。

最佳答案

为此,您将需要 flex column,并在 wrapper 上设置固定高度,这将限制文本的响应速度(当文本可能换行时,wrapper > 不会调整大小)。

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

堆栈片段

.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>


另一种选择是在 wrapper 上使用 background-image,并给它一个左填充(所有这一切都是在没有 Flexbox 的情况下完成的:)。

堆栈片段

.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 时完成,像这样,内联

堆栈片段

.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>

关于html - CSS:使用 flexbox 简化 HTML 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47247939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com