Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Layout - Dynamic width DIV

Tags:

css

width

I have a pretty common layout issue that I have traditionally used a table to solve, but would like some advice on getting it done with CSS. I have 3 images that makeup a 'container'. The left and right images are usually just shown using tags, and the center image is displayed as a 'background-image" with my content over it, so that the content appears to be in the container. I'm sure you've seen/used this a million times:

<table width="100" cellpadding="0"><tr>
<td width="50"><img src="myleftimage" /></td>
<td style="background: url('mymiddleimage');">Content goes here...</td>
<td width="50"><img src="myrightimage" /></td>
</tr></table> 

The nice thing about this is that the width of the table is always the width of the browser (or parent) and the middle column where the content is dynamically sizes to take up the remaining space between the left/right images.

What I want to is recreate this using CSS, with as little hard coded info as possible. So something like this:

<div style="float:left; width:100%">
  <div style="width: 50px;float:left;"><img src="myleftimage" /></div>
  <div style="background: url('mymiddleimage');float:left;width:???">Content goes here...</div>
  <div style="width: 50px;float:left;"><img src="myrightimage" /></div>
</div>

This works great accept for the middle div -how do I set the width? Right now I can hard-code it to be, say, 92%, etc. But want I want is for it to auto-fill the space. Can it be done using only CSS?

like image 899
Todd Davis Avatar asked Aug 31 '09 19:08

Todd Davis


People also ask

How to make auto width in CSS?

Using width, max-width and margin: auto; Then, you can set the margins to auto, to horizontally center the element within its container. The element will take up the specified width, and the remaining space will be split equally between the two margins: This <div> element has a width of 500px, and margin set to auto.

How do I set dynamic width?

Answer: Use the JavaScript width() method You can set the width of a <div> box dynamically using the jQuery width() method.


1 Answers

try

<div style="width:100%;">
    <div style="width:50px; float: left;"><img src="myleftimage" /></div>
    <div style="width:50px; float: right;"><img src="myrightimage" /></div>
    <div style="display:block; margin-left:auto; margin-right: auto;">Content Goes Here</div>
</div>

or

<div style="width:100%; border:2px solid #dadada;">
    <div style="width:50px; float: left;"><img src="myleftimage" /></div>
    <div style="width:50px; float: right;"><img src="myrightimage" /></div>
    <div style="display:block; margin-left:auto; margin-right: auto;">Content Goes Here</div>
<div style="clear:both"></div>    
</div>
like image 107
wow Avatar answered Sep 23 '22 23:09

wow