Reputation: 14250
I am trying to do a text-align center in my elements and I want everything inside that element has text-align left.
Here is my html
<div id='wrapper'>
<div id='inside-wrapper'>
<div>test</div>
<div>test</div>
<div>test</div>
<div>test</div>
</div>
</div>
#inside-wrapper{
text-align:center;
}
#inside-wrapper div{
display:inline-block
text-align:left;
}
The above codes don't work and I need to center my elements like this
----------------------
|
| test test test //inside-wrapper is center but elements inside inside-wrapper is
| test //text-align left
|
I could use margin:0 auto
and setup width for the inside-wrapper
but I am also doing responsive design so I can't really set the width in my inside-wrapper
. How do I resolve this? Thanks.
Upvotes: 0
Views: 72
Reputation: 10454
Your code seems to be working, if you just fix the missing semicolon after display: inline-block
#inside-wrapper div{
display:inline-block; // Missing semicolon here.
text-align:left;
}
As for the last child being centered, you could easily use pseudo selector :last-child
, to float the div left.
Upvotes: 1
Reputation: 9125
Regarding the alignment of elements:
text-align
propertly only applies to text or inline-block
elements (like span
or a
), not block
elements (like div
or p
).I think this is what you're looking for:
HTML:
<div id="Outer">
<div id="Inner">
<div>test</div>
<div>test</div>
<div>test</div>
<div>test</div>
<div>test</div>
</div>
</div>
CSS:
#Outer {
width: 150px;
height: 150px;
background: yellow;
overflow: hidden;
}
#Inner {
width: 100px;
height: 100px;
background: red;
margin-top: 25px;
margin-left: 25px;
}
#Inner div {
display: inline-block;
}
Check the jsfiddle here.
As you may notice, you can use the auto
property to align elements horizontally but you'll need to specify an specific margin-top
size in order to center the inner element vertically; the overflow property must also be set to hidden
, otherwise the margin will push your div down.
Update:
If you don't need to vertically center your inner div, you can stick with this (the inner-div's width is also relative), check this jsfiddle:
CSS:
#Outer {
width: 150px;
height: 150px;
background: yellow;
overflow: hidden;
}
#Inner {
width: 75%;
height: 75%;
background: red;
margin-left: auto;
margin-right: auto;
}
#Inner div {
display: inline-block;
}
By default, all div
's widths are set to 100%
and their heights to wrap their contents, so if you need to center your div without havning to set its width, you should do something like this:
CSS:
#Outer {
width: 150px;
height: 150px;
background: yellow;
text-align: center;
}
#Inner {
display: inline-block;
background: red;
margin-left: auto;
margin-right: auto;
}
#Inner div {
display: inline-block;
}
In this case you can center your inner div with the text-align property but you'll need to set its display property to inline-block
. Check this jsfiddle.
Upvotes: 1