How to align three divs (left/center/right) in one div?
P粉092778585
2023-08-21 15:09:18
<p>I want to align 3 divs inside a container div, like this: </p>
<pre class="brush:php;toolbar:false;">[[LEFT] [CENTER] [RIGHT]]</pre>
<p>The width of the container div is 100% (no width is set), and the middle div should stay in the middle after resizing the container. </p>
<p>So I set: </p>
<pre class="lang-css prettyprint-override"><code>#container{width:100%;}
#left{float:left;width:100px;}
#right{float:right;width:100px;}
#center{margin:0 auto;width:100px;}
</code></pre>
<p>But the result became: </p>
<pre class="brush:php;toolbar:false;">[[LEFT] [CENTER] ]
[RIGHT]</pre>
<p>Any suggestions? </p>
Use Flexbox to align three divs horizontally
This is a CSS3 way to horizontally align a div within another div.
jsFiddle
justify-content attribute has five values:
In all cases, the three divs are on the same line. For a description of each value, see: https://stackoverflow.com/a/33856609/3597276
Benefits of flexbox:
Learn more about flexbox:
Browser Support: Flexbox is supported by all major browsers, except IE < 10. Some recent browser versions, such as Safari 8 and IE10, require the vendor prefix . To quickly add a prefix, use Autoprefixer. See this answer for more details.
Using this CSS, place your div as follows (float first):
Note: You can also float the right first, then the left, and then center. It is important that the floating content comes before the "main" center section.
Note: Usually you will want to add this code at the end of
#container
:<div style="clear:both;">< /div>
, it will make the height of#container
extend vertically to accommodate the floating content on both sides, instead of just being positioned from the height of#center
, like this This prevents content on both sides from overflowing the bottom.