Div Not Centering
I Have a Very Basic % Width Set of Divs. I Am Trying to Center the Element in The. Here Is the Html and Css Code; Html Posted by from Css. Media-Top-Wrapper{...
I have a very basic % width set of divs. I am trying to center the element in the <div class="media-top-center">.
Here is the HTML and CSS code;
HTML
<div class="media-top-wrapper">
<div class="media-top-left">
Posted by <a href="<%= uploader.profilePath %>"><%= uploader.name %></a> from <a href="<%= attribution %>"><%= attribution_name %></a>
</div>
<div class="media-top-center">
<div class="top-center media-card-avatar-round" style="background-image:url('<%= uploader.avatar %>');"></div>
</div>
<div class="media-top-right">
<div class="heart"></div>
<div class="repost"></div>
<div class="flag"></div>
</div>
</div>
CSS
.media-top-wrapper{
max-width: 100%;
margin: 0 auto;
}
.card-media-top-wrapper{
max-width: 100%;
margin: 0 auto;
}
.media-top-left,
.media-top-right{
width: 36%;
float: left;
box-sizing: border-box;
}
.media-top-center{
width: 28%;
float: left;
box-sizing: border-box;
}
.card-media-top-left,
.card-media-top-right{
width: 50%;
float: left;
padding: 0 0.5em 0.25em 0.5em;
box-sizing: border-box;
}
.media-top-left{
padding-top: 1em;
text-align: left;
}
.media-top-center{
text-align: center;
}
.media-top-right{
text-align: right;
}
.top-center{
margin: 0 auto !important;
}
I have centered things before with margin: 0 auto, pretty basic. but in this case, it is not working. Please help.
3 Answers
I am a BIG fan of display: flex;. I think you ought to look into that. Here is my favorite guide for how to center things, and the easiest way is with display flex.
It even takes you through a flow-chart-like experience to get you what you want.
So you can do something like this depending on what your criteria are, exactly:
.media-top-wrapper {
display: flex;
justify-content: space-around;
}
Because .top-center is a div element has for default display:block then is 100% width and margin: auto has no effect. Try changing the display to adjust with the content and center:
.top-center {
display:inline-block;
}
That works because you have on the parent text-align:center
You can't center divs with margin: 0 auto; if you have not set width to element. Add width to .top-center to make it work.
.top-center{
margin: 0 auto !important;
width: 80%; /* add wanted width */
}