I have a container (width is not known) containing four divs, as follows:
| Div1 | Div2 ............... | .............. Div3 | Div4 |
The leftmost and rightmost divs (Div1/Div4) are fixed width; that's the easy part.
The width of Div2/Div3 is not known, and I would like to avoid setting a fixed width for them, as depending on the content one can be much wider than the other (so I cannot just e.g. have each one use 50% of the available space)
I would like the width of Div2/Div3 to be automatically computed by the browser, then if there is any remaining space left, they should stretch to fill any remaining space (it does not matter how the remaining space is split between Div2/Div3)
The way I am approaching this right now is:
My question is, how to have Div2 and Div3 stretch to fill the remaining available width? I guess one option would be to use display: table, and another possibility would be flex-box. Are there any alternatives?
Update: Edited for clarity.
Update 2: Please note that I cannot assume that Div2 and Div3 should each get 50% of the available space. This is explicitly stated in the question but somehow I keep getting answers based on this assumption.
To convert it to a fixed-width layout, simply add a fixed with to the #wrapper and set the margins to auto. Setting the margins to auto will cause the left and right margins to be equal no matter how wide the browser window is, which will cause your fixed-width layout to be positioned in the center of the browser.
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.
The <div> tag defines a division or a section in an HTML document. The <div> tag is used as a container for HTML elements - which is then styled with CSS or manipulated with JavaScript. The <div> tag is easily styled by using the class or id attribute. Any sort of content can be put inside the <div> tag!
I came up with 3 different solutions to get the proper width:
Table cells:
parent: {display: table}
childs: {display: table-cell}
Flex grid:
parent: {display: inline-flex}
childs: {flex-grow: 1}
Box-sizing container:
parent: {float: left}
container: {box-sizing: border-box; padding: 0 WIDTH}
childs: {width: 50%}
The last solution uses extra html markup and aligns elements vertically using relative positioning (means you must have fixed heights).
I suggest you use the first solution, since it's more compatible with older browsers, it's simple to implement and works just fine.
Demo: http://jsfiddle.net/R8mqR/9/embedded/result/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With