How to center the contents of a div [duplicate]

2020-01-25 07:58发布

I have a very simple problem, but I can't seem to solve it. I have a table inside a div, which is the main element. Now I have a td tag inside the table with a width and hight set to that of an iphone screen size. Now I basically want to center that table with its td cell within the div tag, so that the 'screen' will be centered in any browser window. How do I do that?

Replacing that div with a table solved my problem, but I would like to use a div instead.

Thank You

标签: html css
5条回答
一纸荒年 Trace。
2楼-- · 2020-01-25 08:30
<style type="text/css">
.outer { width:800px; height:640px; }
.inner {
    position:relative; top:50%; left:50%;
    width: 320px;
    margin-left: -160px; /* half the width */
    height: 240px;
    margin-top: -120px; /* half the height */
</style>

<div class="outer">
    <div class="inner">I'm centered!</div>
</div>
查看更多
3楼-- · 2020-01-25 08:30

HTML

    <div class="img_thumb">
    <table>
        <tr><td>adfasfdasf</td></tr>
        <tr><td>adfasfdasf</td></tr>
        <tr><td>adfasfdasf</td></tr>
        <tr><td>adfasfdasf</td></tr>
        <tr><td>adfasfdasf</td></tr>
    </table>
</div>

CSS

.img_thumb {
    background: none repeat scroll 0 0 red;
    display: table-cell;
    height: 200px;
    vertical-align: middle;
    width: 200px;

}
table {
    border: 1px solid;
    width: 100px;
    margin:auto;
}

or see the demo:- http://jsfiddle.net/QHEnL/16/

查看更多
一纸荒年 Trace。
4楼-- · 2020-01-25 08:40

I haven't tested in IE (works in FF and Safari), but if you're using jQuery you could use this to center a div with the class page within the page:

var pageMargin = ($(document).width() - $("div.page").width()) / 2;
$("div.page").css("margin-left", pageMargin).css("margin-right", pageMargin);
查看更多
Rolldiameter
5楼-- · 2020-01-25 08:41

try this:

div#centerlayout 
{ 
    position:absolute; 
    left:50%; 
    top:50%; 
    height:XXXpx; 
    width:XXXpx; 
    margin-top:-XXXpx; 
    margin-left:-XXXpx; 
} 
查看更多
太酷不给撩
6楼-- · 2020-01-25 08:52

Try this one , I do this code - Demo here, Very easy and simple code ( I have used a hack code and extra span tag for only IE old version) http://jsfiddle.net/ERuX4/1/

<div class="demo wraptocenter">
   <span></span>
   <img src="http://www.spitzer.caltech.edu/images/twitter.png?1295473781" alt="" />
</div> 

css

.wraptocenter * {
    vertical-align: middle;
}
.wraptocenter span {
    display: inline-block;
    height: 100%;
    width: 1px;
}
.wraptocenter {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}

/*End wraptocenter - image Vcenter  patch styles*/    
.demo  {
         width:100px;
         height:100px;
         border:1px solid red;
         position:absolute;
         top:50%;
         left:50%;
         margin-top:-100px;
         margin-left:-100px;}
查看更多
登录 后发表回答