简体   繁体   中英

Centering Dynamic width Divs

I have a page that has 2 columns. The first column is a dynamic width. It contains a bunch of tabular data in tables. The 2nd column is a fixed width full of navigation stuff.

The 2 columns are divs with float left. I need to accomplish 2 things.

  1. I need to center the 2 divs on the page. For example, if the first div is 600px wide as dictated by the data inside of it and the second div is a fixed 200px, the centering point is 400px.

  2. I don't want the 2nd div to wrap down if the browser window is resized.

I'm thinking that I may have to nest the 2 divs inside of another div, set the parent div width using javascript, then center it.

I created this fiddle to help illustrate. http://jsfiddle.net/darthg8r/uhKdt/

Surround them with a div and set its style to:

width: ( whatever you need )
margin: 0 auto; // this centers the div

You can set the width dynamically with JavaScript if needed. As long as it's smaller than 100% of the surrounding container, it will stay centered.

You could achieve this with the following code:

HTML:

<div id="wrapper">
    <div id="container">
        <div id="variable">test</div>
        <div id="fixed">test</div>
    </div>
</div>

CSS:

#wrapper { overflow: hidden; }
#container { 
    float: left;
    position: relative;
    left: 50%; }
#container > div {
    float: left;
    position: relative;
    right: 50%;
    height: 300px; }
#variable { 
    background: red;
    width: 300px; }
#fixed { 
    background: blue;
    width: 200px; }

Preview: https://jsfiddle.net/Wexcode/mreLt/

You could also achieve this effect by wrapping the two elements in a container, setting them both to display: inline-block , and finally setting their container to have text-align: center .
The answer is a little more complicated than this, so let me know if you want to choose this route instead.

To make it so the elements don't fall to the next line, use inline-block .

<div id="container">
    <div id="variable">
        <p>test</p>
    </div><div id="fixed">
        <p>test</p>
    </div>
</div>

CSS:

body { margin: 0; }
#container { 
    color: #fff;
    text-align: center;
    white-space: nowrap; }
#container > div {
    height: 300px;
    display: inline-block; }
#variable { 
    background: red;
    width: 100px; }
#fixed { 
    background: blue;
    width: 200px; }

Preview: https://jsfiddle.net/Wexcode/mreLt/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM