I have some element, div or whatever with id and i want to center it on webpage. But when it looks good on computer screen, it looks bad on mobile. How to center it correctly, with any framework like bootstrap or something, or without, any method, jquery also is possible. It has too looks good on all mobile and all computer browsers. Thanks.
-
have you tried `text-align: center` ? – neo Jan 09 '15 at 20:22
-
2possible duplicate of [Best way to center aon a page vertically and horizontally?](http://stackoverflow.com/questions/356809/best-way-to-center-a-div-on-a-page-vertically-and-horizontally)– JohnP Jan 09 '15 at 20:23
4 Answers
I will give you another solution to position at absolute center (horizontal and vertical) that never fails and works on every browser I've tested (ie 8+).
You have the HTML
<div id="centered">
<!-- Place your content here -->
</div>
And here is the CSS for absolute center(horizontal and vertical) :
#centered{
width: 500px;
height: 500px;
position:absolute;
top:0;
right:0;
bottom:0;
left:0;
margin:auto;
}
Here is if you want only vertical :
#centered{
width: 500px;
height: 500px;
position:absolute;
right:0;
left:0;
margin:auto;
}
And only horizontal :
#centered{
width: 500px;
height: 500px;
position:absolute;
top:0;
bottom:0;
margin:auto;
}

- 1,218
- 5
- 21
- 47
It is very simple. HTML
<div id="container">
<div id="content">
Your content here. It can be text, image or anything.
</div>
</div>
CSS
#container{
width:auto;
height: auto;
}
#content{
width:90%
height:90%;
margin:auto;
}
NOTE: margin auto actually center the alignment sometimes it depend on the scenario. Where there is a fixed height and width, it more easy. GOODLUCK
TIP
If you want to see the alignment of , you should use #selector{border:solid};
in CSS during design and then you can remove it..

- 826
- 5
- 16
Try this:
<div class="center">
<p>.........content...........</p>
</div>
Now CSS:
.center{
margin:0 auto;
width:500px; /*adjust your width*/
}

- 303
- 3
- 12
CSS
.flexme{
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
}
HTML
<div class = 'flexme' style = 'position:absolute; top:0; bottom:0; right:0; left:0; '>
<div id = 'div_you_want_centered' style = 'margin:auto;'>
This will be Centered
</div>
</div>
Check out http://css-tricks.com/snippets/css/a-guide-to-flexbox/
The first div takes up the whole screen and has a display:flex set for every browser. The second div (centered div) takes advantage of the display:flex div where margin:auto works brilliantly.
Note IE11+ (IE10 w/ prefix)

- 11,558
- 11
- 61
- 87