You are here:Home»KB»Web Design»HTML»Centre Floats
Friday, 18 December 2015 18:41

Centre Floats

Written by

These techniques all center floats, they do not replace the floats with other code like some people suggest. All of these methods dont seem to need to have the widths set, if you run into problems you might consider setting the widths of the child elements (ie the ones that are floated).

display: table Method

Optional Title

Content Here

Optional Title

Content Here

Width set to 150px

Optional Title

Content Here

Optional Title

Content Here

No set width

<div class="float-parent" style="display: table; margin: auto; border: green 3px solid;">
	<div style="float: left; margin: 5px; width: 150px; border: blue 3px solid;">
		<h3>Optional Title</h3>
		<p>Content Here</p>
	</div>
	<div style="float: left; margin: 5px; width: 150px; border: blue 3px solid;">
		<h3>Optional Title</h3>		
		<p>Content Here</p>
	</div>
</div>

This is my prefered method and uses the least amount of code. The way it works is display: table; make the browser treat the immediate children as Table cells so the floats actuall only occur within the table cell.The table is then centered with margin: auto; .

position:relative Method

 

CSS Code

<style type="text/css">
	#centered-float-menu {
		float: right;
		position: relative;
		left: -50%;
		border: green 3px solid;
	}

	#centered-float-menu ul {
		position: relative;
		left: 50%;
		border: yellow 3px solid;
	}

	#centered-float-menu li {
		float: left;
		border: blue 3px solid;
	}
</style>

HTML Code

<div id="centered-float-menu">
	<ul>
		<li><a href="#">Link 1</a></li>
		<li><a href="#">This is long...</a></li>
		<li><a href="#">Link 3</a></li>
		<li><a href="#">www.myexampledomain.com</a></li>
		<li><a href="#">Link 5</a></li>
	</ul>
</div>

This relative method is a work around but does do what it says on the tin and might be useful when the preferred method does not work.

 text-align: center; and inline-block Method

Link 1
Link 2
Link 3
<div style="text-align: center; border: green 3px solid;"> 
	<div style="display: inline-block; border: yellow 3px solid;"> 
		<div style="float: left; margin: 2px; border: blue 3px solid;">Link 1</div> 
		<div style="float: left; margin: 2px; border: blue 3px solid;">Link 2</div> 
		<div style="float: left; margin: 2px; border: blue 3px solid;">Link 3</div> 
	</div> 
</div>

This method does maintain the floats, it is not like other tutorials where they instruct you to replace the floats with the inline-block centre method.

Links

Read 801 times Last modified on Saturday, 19 December 2015 14:12