Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have vertically centered text wrap around a floating image

Tags:

html

css

I'm not entirely sure how to describe it better than the title, so I'll just draw it.

In the below images, the horizontal lines are the "text", the small box is the image, and the bigger box is the whole webpage. I want the text to behave like it does in the drawings and I have no idea how.

vertically centered text next to an image

text wrapping around a floating image

I can get the text to wrap around the image using float, and i can get the text vertically centered using flexbox or grid or table, but i can't do both at the same time. Using any of those techniques to vertically center the text appears to encounter the clearing bug and they basically treat height:100% as if the image wasn't there.

parent of text that needs to be vertically centered obeys clearfix

child does not obey clearfix

like image 256
reticivis Avatar asked Dec 20 '25 20:12

reticivis


1 Answers

You can achieve with help of float and flex properties. So you will need to check dynamically small amount of text if exist then add .box-flex class in .box if amount of text is more then don't need to add .box-flex class.
With flex display I am using order property for transform image div from left to right.

I hope below snippet will help you a lot.

*{box-sizing: border-box;}
.box{
    font-family: Arial;
    font-size: 16px;
    line-height: 22px;
    width: 100%;
    max-width: 480px;
    min-height: 100px;
    background-color: rgb(148, 206, 203);
    padding: 15px;
    margin: 15px auto 15px auto;
    color: #333;
    border-radius: 8px;
}
.img{
    width: 100px;
    height: 100px;
    min-width: 100px;
    max-width: 100px;
    max-height: 100px;
    background: coral;
    margin-left: 12px;
    float: right;
    border-radius: 4px;
}
.txt{
    position: relative;
    min-height: inherit;
    padding: 0;
    text-align: justify;
}
.box-flex{
    display: flex;
    justify-content: space-between;
}
.box-flex .img{
    order: 1;
}
.box-flex .txt{
    padding: 0;
    align-self: center;
    min-height: auto;
}
<div class="box box-flex">
    <div class="img"></div>
    <div class="txt">
        If small amout of text (use .box-flex)
    </div>
</div>
<div class="box">
    <div class="img"></div>
    <div class="txt">
        Lorem ipsum dolor sit amet conse ctetur adipis icing elit. Unde adipisci soluta beatae minima, dolores atque voluptas, explicabo mollitia, sunt alias nihil dolo ribus veritatis perfe rendis quib usdam error exerci ationem quia conseq uuntur eos digni ssimos sed veniam? Rerum saepe qui sed corporis volupt atibus soluta quo eaque. Quidem recu sandae dolorum nesciunt Rerum saepe qui sed.
    </div>
</div>
like image 85
Raeesh Alam Avatar answered Dec 22 '25 11:12

Raeesh Alam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!