Kristian Rafteseth
Kristian Rafteseth

Reputation: 2032

CSS: Dynamic width of element inside div

How can I go about making the floating-text div below have a dynamic width, so it will fill the space beside the image? The image can be all from 100px to 400px wide.

<div id="container">
  <img src="image-can-be-from-100-to-400px-wide.jpg">
  <div id="floating-text">
    Text to be floated:left on right side of the image.
    The width of this div needs to be dynamic, 
    so it will fill out the open space on the right side of the image above.
  </div>
</div>

The css:

#container {
  width: 700px;
  padding: 20px;
}
#floating-text {
  margin-left: 20px;
  float: left;
}

Fiddle: http://jsfiddle.net/51zstw6b/

Upvotes: 1

Views: 176

Answers (5)

Gold Pearl
Gold Pearl

Reputation: 2024

CSS

#container {
  width: 700px;
  padding: 20px;
}

#container img
{
    float:left;
}

#floating-text {
  margin-left: 20px;
  float:left;
    width:200px;    
}

Upvotes: 0

Anupam Basak
Anupam Basak

Reputation: 1523

The easiest thing you could think of is using a CSS Flexbox

HTML :

<div id="container">
    <img src="http://placehold.it/100x100/aaaaaa/444444.png&text=400x400" />
  <div id="floating-text">
    Text to be floated:left on right side of the image.
    The width of this div needs to be dynamic, 
    so it will fill out the open space on the right side of the image above.
  </div>
</div>

CSS :

#container {
    display: flex;
    flex-direction: row;
    width: 700px;
    padding: 20px;
    background: red;
}
img {
    display: flex;
    margin-right: 20px;
}
#floating-text {
    display: flex;
    flex:1;
}

Here is the Fiddle : http://jsfiddle.net/94bLqe9d/

Upvotes: -1

Kristofer Gissl&#233;n
Kristofer Gissl&#233;n

Reputation: 1320

That depends on what your working with. If you want to keep old browsers happy you could add an align property to the image. align="top" for instance tells the image to float text to the top of the image. This doesn't float the image, it actually tells the text to wrap around the image.

If you're using modern standards you can replace it with a css-class like this:

.float-image {
    float: left;
    margin-right: 10px;
}

This should float your text around the image and add a proper margin so the text wouldn't wrap into the image.

Upvotes: 1

anpsmn
anpsmn

Reputation: 7257

Give image a float: left and remove the float for the floating-text.

CSS

#container {
  width: 500px; /*width adjusted for this fiddle demo*/
  padding: 20px;
}

.img {
    width: 200px;
    float: left;
    margin-right: 5px;
}

#floating-text {
  margin-left: 20px;
}

See Fiddle

Upvotes: 2

ArinCool
ArinCool

Reputation: 1738

Can you try this CSS:

#floating-text {
  float: left;
   width: 40%;
}
img {
    float:left;
    width: 60%;
}

Note: the css on #container is removed

Upvotes: 0

Related Questions