开发者

How to center a Div across all Monitors/Resolutions/Browsers?

I have created my own light box, the problem is that it shows centered开发者_运维技巧 on my monitor but not on wider monitors or bigger resolutions.

What is the best way to center a div across all resolutions/monitors/browers?


Centered horizontally, vertically or both? If you want both, this has worked for me in the past. Otherwise, the answer sathish posted is good for horizontal only centering


Try using this

Make parent div style as center and use margin: 0 auto; to the child div

#parentDiv{
text-align: center;
}

#main{
margin:0 auto;
width:755px;
text-align: left;
}

<div id="parentDiv"><div id="main">Content</div></div>


#center {position:absolute; width:400px; height:400px; left:50%; top:50%; margin:-200px /must be half of the height/ 0 0 -200px; /must be half of the width/}

that will center the div horizontally and vertically. In relation to its first parent with the position:relative;


if you know the width:

<div></div>

div {
  left: 50%;
  margin-left: -50px; /* width / 2 */
  width: 100px;
}


well if you set everything to be centered using

*{margin:0 auto;}

it will center anything in your document unless told otherwise

or you can use a wrapper div

div#wrapper {margin:0 auto;}

if your using older browser you should use

div#wrapper {text-align:center;}

there is like 30 ways of doing it, kinda depends on what your doing...

these are the most easy ones


Set a width on the div and then give it a centering class:

.center
{
margin:0 auto;
}

It will be centered in any browser.


although all the answers above seem correct i did get stuck on this myself for a moment. Here is my simplified approach.

Let's say you have the code below and you want to center the content within the div 'storyline-container'.

<body>
    <div class="storyline-container">
        <script src=storyline.js type="text/javascript"></script>
    </div>
</body>

Simply writing the code below won't work because you also need to center align the parent div which in this case is the 'body'

.storyline-container 
{
    text-align: center;
}

Add the code below in your css file to solve your problem.

body{
    text-align: center;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜