Lion
Lion

Reputation: 121

Centering something without margin

Is it possible to center something without using margin: auto;? My div cannot be a set size because the width will change according to it's contents and even so I would not know how wide it would be since it's text inside (There is a div around text because there are multiple <p>'s). Is there any other way of aligning in center without knowing your width of the object?

div#contents {
	display: inline-block;
	margin: 50px 100px 50px 100px;
	border: 3px solid black;
}

table#socialmedia {
	height: 100px;
	margin-top: 10px;
	float: left;

}

table#support {
	height: 25px;
	margin-top: 10px;
	float: left;

}

table#external {
	margin-top: 10px;
	float: left;

}

div#footerdivider {
	width: 1px;
	height: 120px;
	margin: 0px 50px 0px 50px;
	background-color: #424242;
	float: left;
}

p.footerlinks {
	font-size: 20px;
	color: #8C8CFF;
	text-align: center;
<div id="contents">
	<table id="socialmedia">
		<tr><td><a href=""><p class="footerlinks">Facebook</p></a></td></tr>
		<tr><td><a href=""><p class="footerlinks">Twitter</p></a></td></tr>
		<tr><td><a href=""><p class="footerlinks">YouTube</p></a></td></tr>
		<tr><td><a href=""><p class="footerlinks">Steam</p></a></td></tr>
	</table>
	<div id="footerdivider">
	</div>
	<table id="support">
		<tr><td><a href=""><p class="footerlinks">Email Us (Click to copy)</p></a></td></tr>
	</table>
	<div id="footerdivider">
	</div>
	<table id="external">
	</table>
</div>

Upvotes: 2

Views: 173

Answers (3)

Jhey
Jhey

Reputation: 1377

To center align an item without the use of margin: 0 auto;, you could use flexbox if the browsers you are working with support it.

Consider the following snippet;

.container {
    display: flex;
    justify-content: center;
    margin: 5px 0;
}
.item {
    background-color: red;
    border: 1px solid black;
}
<div class="container">
    <div class="item">Lorem ipsum dolor sit amet.</div>
</div>
<div class="container">
    <div class="item">Praesent ultrices nec quam at blandit. Pellentesque elementum ullamcorper lobortis.</div>
</div>

There is a good article on flexbox over @ css-tricks.com you can check out here.

Hope that helps you out!

Upvotes: 1

Biboy
Biboy

Reputation: 36

Try

div.your_element {
  display: table;
  margin: 0 auto;
}

display: table (to center a fluid div:)

margin: 0 auto (to center tables)

Upvotes: 1

moongom
moongom

Reputation: 29

I'think if you set the margin to auto. It is usually working on horizontal.

div {
      margin: auto;

}

Upvotes: 0

Related Questions