Amira
Amira

Reputation: 3270

How to center a component without knowing its width in Css

How to center a component without knowing its width value. I know that you can position a component in the center by writing this in css:

Width: componentWidth; 
margin: auto;

But in my case it's a generic style (given to different kind of buttons with different with value).

Any Help will be appreciated

Upvotes: 1

Views: 133

Answers (4)

TheLovelySausage
TheLovelySausage

Reputation: 4094

You can do it without CSS or knowing an elements size using a table if you want to get old school.

<table width="100%">
<tr>
    <td align="center"><!-- anything in here will be centered --></td>
</tr>
</table>

Here's an example

https://jsfiddle.net/gxyyecdy/

Upvotes: 1

Dark Hippo
Dark Hippo

Reputation: 1265

I'd suggest using display:flex and justify-content:center on your container.

For example

HTML

<div class="container">
  <span class="content">Center!</span>
</div>
<hr />
<div class="container2">
  <span class="content2">Center 2!</span>
</div>

CSS

.container {
  display:flex;
  justify-content:center;
  border:solid 1px red;
}

.container2 {
  display:flex;
  height:200px;
  justify-content:center;
  align-items:center;
  border:solid 1px red;
}

Fiddle here

The second container is an example of how to vertically center something, as an added bonus.

Upvotes: 4

Mr. Alien
Mr. Alien

Reputation: 157334

margin: auto; will work when you have some fixed width defined to your element, if you have dynamic width, you can use transform: translateX(-50%); to center your element horizontally(which I assume is what you want) or you can add translateY(-50%) if you want to center vertically.

For example:

div {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-50%);
  /* specifying x and y separately on purpose so that you understand whats going 
     on and what you can remove what you don't need from the above snippet */
}

Demo

If you want just horizontal centered element, get rid of top: 50% and translateY(-50%) respectively. Just note that it's a good practice to nest your absolute positioned element inside relative positioned element.

Upvotes: 2

Anthony E
Anthony E

Reputation: 11235

In order for margin: auto to work, you must also have block as the display type. The display type for links and buttons is inline-block by default, so override this with display: block; in your style:

.whatever-your-btn-class-is {
  margin: auto;
  width: componentWidth;
  display: block;
}

Upvotes: 1

Related Questions