Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

text-align center being affected by float elements

Tags:

I have two float elements, right and left.

The parent element for all of them is text-align: center, margin: auto:

<div class="test"> 1. text     <br>     <span id='small_font10' style='float: left;'>999</span> <a class='writeSComment' id='small_font10' data-id='<?php echo $id; ?>' style='cursor: pointer'> <strong>2. text</strong> </a> <span id='small_font10' style='float: right;'>  Follow me </div> 
.test{     width: 500px;     text-align: center;     margin: auto;     background: red; } 

http://jsfiddle.net/KRWNs/

If you see the 1. text, there's the center. The 2. text is moving ( being affected from the float elements) to the left as you can see, and are not center.

How can I make this align as the normal above (as the 1. text), without being affected by the float elements on the right and left side?

like image 509
Karem Avatar asked Dec 19 '10 19:12

Karem


People also ask

How do you center text in float?

To center the text using float we can use margin-left or margin-right and make it 50% , like below.

How do you center a floated element in CSS?

The CSS float property is used to set or return the horizontal alignment of elements. But this property allows an element to float only right or left side of the parent body with rest of the elements wrapped around it. There is no way to float center in CSS layout.

How do I center a floated div?

First, remove the float attribute on the inner div s. Then, put text-align: center on the main outer div . And for the inner div s, use display: inline-block . Might also be wise to give them explicit widths too.

What is the difference between float and text-align?

float moves the element itself, text-align moves the text inside the element.


1 Answers

You'll need to use something other than float to stick the elements to the sides. As it is, they are behaving as they are supposed to. Here's an updated example using absolute positioning to stick to the sides. Very long content will not honor the elements, however.

Alternatively, as seen in this test, you need to ensure that both floats are the same width.

The fact that the outer element is "margin auto" is irrelevant.

like image 140
Phrogz Avatar answered Oct 28 '22 23:10

Phrogz