Patrick Szalapski
Patrick Szalapski

Reputation: 9439

How to center without taking into account a floated element?

In styling a page, suppose I have an element that I want to float:right, and before it I have an inline element I want to horizontally center without regard to the floated element. I can only get it to center between the floated element and the margin; I want it to ignore the floated element and center in its container.

<div class="container">
    <span class="headline">this Needs centering</span>
    <span class="corner-tag">without regard to this<span>
</div>

With my first try of styles:

.container {text-align: center; } 
.corner-tag {
    border: 1px solid black;
    float: right; 
}

Here's the fiddle:

http://jsfiddle.net/szal/6zgbw/

Can I modify the styles without modifying the markup to achieve this?

Upvotes: 1

Views: 119

Answers (2)

CaribouCode
CaribouCode

Reputation: 14428

You can do this by taking either .headline or .corner-tag out of the flow using absolute positioning:

.container { text-align: center; }

.headline { 
    position: absolute; 
    z-index: 10; }

.corner-tag {
    position: relative;
    z-index: 20;
    border: 1px solid black;
    float: right; }

Fiddle: http://jsfiddle.net/6zgbw/1/

Upvotes: 0

Floremin
Floremin

Reputation: 4089

Unless you absolutely need to use float:right; you can try something like this:

.container {
    text-align: center;
    position: relative;
}
.container-tag {
    border: 1px solid black;
    position: absolute;
    right: 0;
}

Here is JSFiddle: http://jsfiddle.net/6zgbw/2/

Upvotes: 3

Related Questions