Intra
Intra

Reputation: 2109

Float left combined with center element

How can I center the second element in a div without knowing the width of the first.

I want "foo" to float to the left and "bar" to be centered in the original div. I can do this if I know the width of "foo":

<div>
    <span style="float:left;">foo</span>
    <span style="margin-left:-10px;">bar</span>
</div>

Is there another way to do this, without margin-left set to a static width?

Upvotes: 1

Views: 571

Answers (4)

sandeep
sandeep

Reputation: 92803

You can write like this:

CSS

.parent{
    text-align:center;
}
.child1,.child2{
    text-align:left;
}
.child1{
    float:left;
}
.child2{
    vertical-align:top;
    display:inline-block;
    *display:inline;/* For IE7 */
    *zoom:1;/* For IE7 */
    border:1px solid red;
}

HTML

<div class="parent">
    <span class="child1">foo</span>
    <span class="child2">bar</span>
</div>

Check this http://jsfiddle.net/6fMve/1/

Upvotes: 0

Wex
Wex

Reputation: 15695

I'm a little confused as to why you'd want this, but here: http://jsfiddle.net/Wexcode/jL87v/

<div>
    <span class="foo">foo</span>
    <span class="bar">bar</span>
</div>

CSS:

.foo { float: left; }
.bar {
    text-align: center;
    margin: 0 auto;
    display: block; }

Upvotes: 0

Supr
Supr

Reputation: 19012

Center of the parent div?

<div>
    <span id="f"> foo  foo  foo  foo  foo  foo  foo  foo </span>
    <span id="c">bar</span>
</div>

CSS:

#f{
    float:left;
}
#c{
    display:block;
    margin: 0 auto;
    width:100px;
}

Upvotes: 5

Kevin Schueller
Kevin Schueller

Reputation: 77

Try setting the margin-left on the second element to 50%.

Here's an example: http://jsfiddle.net/6fMve/

Upvotes: -1

Related Questions