Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting a Border Around Floating Elements

Say I have something like the following code, where I want to display some text between two images that I am floating left and right.

<img src="testImage1.png" alt="Test Image 1" style="float:right;" /> <img src="testImage2.png" alt="Test Image 2" style="float:left;" /> <p>Test Text</p> 

I want to add a border around the two images and the text. I tried putting a <div> around all 3 of the above tags and using style="border:2px black solid;". While this adds a border, it seems to not take the images into account. That is, we get something like the following (using StackOverflow and Google logos).

enter image description here

I am guessing this is happening because the floating elements are not being considered as part of the <div>. I am a software developer, not a web developer, so I am no expert in CSS. But I do think I recall that floating elements are kind of "ignored" in a way. Can anyone give a detailed description of what is going on and how to fix it?

like image 601
Snowy Coder Girl Avatar asked Jan 04 '12 01:01

Snowy Coder Girl


People also ask

How do you put a border around an element?

Borders can be applied to most HTML elements within the body. To make a border around an element, all you need is border-style . The values can be solid , dotted , dashed , double , groove , ridge , inset and outset .

How do you put a space between a picture and a border?

You can use Padding in your style attribute or CSS class. Show activity on this post. Padding allows you to control the space between your image and its border. Padding is just one piece of a larger concept, the CSS Box Model, which includes the content, padding, border and margin.

How do you center a floating element?

There is no way to float center in CSS layout. So, we can center the elements by using position property.


2 Answers

Adding an overflow in this case with a value of hidden or auto remedies the issue.

Check the fiddle below:

http://jsfiddle.net/XMrwR/

Clearing floats the overflow way

http://www.quirksmode.org/blog/archives/2005/03/clearing_floats.html

like image 179
Alex Avatar answered Sep 22 '22 15:09

Alex


In CSS, floated elements do not add height to a parent by default.

The solution is simply to set overflow: hidden.

<div style="border: 2px solid black; overflow: hidden;"      <img src="testImage1.png" alt="Test Image 1" style="float:right;" />     <img src="testImage2.png" alt="Test Image 2" style="float:left;" />     <p>Test Text</p> </div> 

fiddle: http://jsfiddle.net/JNets/

like image 29
benesch Avatar answered Sep 19 '22 15:09

benesch