简体   繁体   中英

aligning icon based on text length

I have a title text and an icon.

I need to align the icon to the left if the title can accomodate in single line.

If the title covers more than 1 line, then I have to align the icon to the top.

I found a solution using Javascript, by appending a dynamic class based on the height and lineheigth.

Is there any way to achieve only using css? 在此处输入图像描述

This sounds like something that could be solved with flex .

You are looking for the property flex-wrap . In your case, flex will keep your items inline, unless one becomes too long, in which case it will wrap it to the next line.

The CSS code would look something like this:

.item{
    display:flex;
    justify-content:center;
    flex-wrap:wrap;
}
.icon{
    flex-shrink:0;
}

The HTML should look something like this:

<div class="item">
    <div class="icon"></div>
    <div class="text">aaaaaaaaaa</div>
</div>
<div class="item">
    <div class="icon"></div>
    <div class="text">
        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
    </div>
</div>

Your item would be the one that you should assign flex to.

Have icon as a pseudo element like i have added via css.

 div{ margin: 1em 0; border: 1px solid black; padding: 2em; position: relative; } div::before { position: absolute; left: 0; content:"icon"; }
 <div>My Content</div> <div>My Log ContenttttttttttttttttttttttttttttttttttttMy Log ContenttttttttttttttttttttttttttttttttttttMy Log ContenttttttttttttttttttttttttttttttttttttMy Log ContenttttttttttttttttttttttttttttttttttttMy Log ContenttttttttttttttttttttttttttttttttttttMy Log ContenttttttttttttttttttttttttttttttttttttMy Log ContenttttttttttttttttttttttttttttttttttttMy Log ContenttttttttttttttttttttttttttttttttttttMy Log Contentttttttttttttttttttttttttttttttttttt</div>

First you add icon and text elements in root element.

<div class="root"> <div class="icon">Icon</div> <div class="text">Text</div> </div>

This root element styles:

.root{ display: flex; flex-wrap: wrap; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM