I have four divs contained in another div, and I want the four inner divs to be centered.
I have used float: left
on the four divs so that they are horizontally aligned.
CSS:
<style> .square //inner divs { float: left; margin:1pt; width:72pt; height:72pt; } .container //outer divs { text-align:center; width:450pt; height: 80pt; } </style>
and HTML:
<div class = "container"> <div class = "square">...</div> <div class = "square">...</div> <div class = "square">...</div> <div class = "square">...</div> </div>
How can I center the divs inside the container?
The number of inner divs can be variable.
You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.
Vertically centering div items inside another div Just set the container to display:table and then the inner items to display:table-cell . Set a height on the container, and then set vertical-align:middle on the inner items.
CSS – Horizontally Center Multiple DivsSet text-align attribute for outer div as center. Make sure the inner divs are inline blocks.
Because you don't know the number of divs you have, you should use
text-align:center
on the outer div
display:inline-block
on then inner div
http://jsfiddle.net/edi9999/yv2WY/
HTML
<div class = "container"> <div class = "square">John</div> <div class = "square">Mary</div> <div class = "square">Doe</div> <div class = "square">Jane</div> </div>
CSS
.square { margin:1px; width:20%; text-align:left; border: 1px solid gray; display:inline-block; } .container { text-align:center; width:100%; height: 80pt; border: 1px solid black; }
Here's an alternate method if you can use an extra div:
<div class = "container"> <div class="centerwrapper"> <div class = "square">...</div> <div class = "square">...</div> <div class = "square">...</div> <div class = "square">...</div> </div> </div> <style> .square { float: left; margin:1pt; width:72pt; height:72pt; } .container { text-align:center; width:450pt; height: 80pt; } .centerwrapper { margin: auto; width: 302pt; } </style>
Also, make sure you have a closing quote on your <div class = "container">
there. The code you pasted is missing one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With