Tober
Tober

Reputation: 228

CSS make sure text next to image has enough space

I'm making a responsive webpage. In the screens you see the problem in the 3th image. The space for the text is to small to fit normally. I could fix this problem by using javascript, but i prefere just using CSS3. All elements are inline and the size of the image is dynamic. It can be that the image is 50px (img 1), but it can also be that the image is big enough for full width (img 2).

example

my html:

<h2>title</h2>
<div class="newsItemImage"></div>
<p class="newsItemText"></p>

my css:

#pageNewsItem h2 {
    margin: 10px 15px;
}

.newsItemImage {
    float: left;
    margin: -15px 0 -5px 0;
    max-width: 100%;
    border: 15px solid rgba(0, 0, 0, 0);
    box-sizing: border-box;
}

.newsItemText {
    margin: 0 15px 15px 15px;
}

I use a invisible border and box-sizing because otherwise I can't use max-width and give it a margin. If anyone knows a better sollution for this aswell feel free to tell me.

Thanks in advance!

Upvotes: 2

Views: 2654

Answers (3)

Tober
Tober

Reputation: 228

Thanks for the sollutions, but I already found my best option. I added a element after the image and gave it the css:display:inline-block; width:150px. Now if the space next to the image is less than 150px, this element automatically jumps under the image and so does the text.

full code:

HTML:

<h2 class="pageHeaderH2">BREEAM - globale milieu - beoordeling van gebouwen</h2>
<img src="img/dummyImages/newsItemThumb1.jpg" id="newsItemImage">
<div id="minSpace"></div>
<p class="newsItemText">Lorem ipsum dolor sit amet, con ... iaculis ul</p>

CSS:

#pageNewsItem h2 {
    margin: 10px 15px;
}

#newsItemImage {
    float: left;
    margin: -15px 0 -5px 0;
    max-width: 100%;
    border: 15px solid rgba(0, 0, 0, 0);
    box-sizing: border-box;
}

#minSpace{
    display:inline-block;
    width:150px;
}

.newsItemText {
    margin: -15px 15px 15px 15px;
}

Upvotes: 2

AstralProgrammer
AstralProgrammer

Reputation: 168

You can set either the <p> or <span> you are using for the text or the <img> with {display:block;} to clear other element.

It is best if you can provide the HTML code so we could check the structure.

Upvotes: -1

RichieAHB
RichieAHB

Reputation: 2088

CSS can't be used to perform calculations on the size of content. I recommend you standardise the size of the image on the left by putting it in a container of a certain size (most likely a percentage width for responsive sites) and then forcing the image to take this width know width. Then you can use your responsive breakpoints to bring the text below the image accurately in every case.

Upvotes: 1

Related Questions