Center a DIV to the center of page regardless of s

2019-02-14 03:22发布

问题:

I want to center the below div container to that the site appears in the center of the page, regardless of the screen size.

http://penarthpc.com/~droneboy/

I've played around a little bit but appear to be missing something.

回答1:

The solution to this problem is using auto for margin in the CSS AND providing some width to the DIV itself:

div.centered {
margin-left:auto;
margin-right:auto;
width:80%;
}


回答2:

Easiest way to center something regardless of page width is margin: auto; in your CSS, with height and width defined.

.class {
    height: 50px;
    width: 50px;
    margin: auto;
}

JSFiddle: http://jsfiddle.net/rVXBH/



回答3:

.center-div {
   width: 600px;
   height: 600px;
   position: absolute;
   left: 50%;
   top: 50%; 
   margin-left: -300px;
   margin-top: -300px;
}

This will center your DIV with class center-div horizontally AND vertically. The margin-left must be negative half of what your width is. The margin-top must be negative half the height.

To just center horizontally:

.center-div {
   width: 600px;
   height: 600px;
   position: relative;
   margin-left: auto;
   margin-right: auto;
}


回答4:

if you want to center the container (vertical) :

vertical centering with css

if (horizontal) look at this :

how-do-you-easily-horizontally-center-a-div



回答5:

simple. Just give the container margin of "0 auto"

margin: 0 auto;


回答6:

Here is a great method I use, it makes use of a before selector to create a invisible div that takes care of the vertical alignment:

HTML:

<body>
    <div id="outter-div">
        <div id="aligned">
            <h1>A Nice Title</h1>
            <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam</p>
        </div>
    </div>
</body>

CSS:

/* This parent can be any width and height */
#outter-div {
  text-align: center;
}

/* The ghost, nudged to maintain perfect centering */
#outter-div:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */
}

/* The element to be centered, can
   also be of any width and height */
#aligned{
  display: inline-block;
  vertical-align: middle;
  width: 300px;
}

This can be found on this post which also has a demo on jsbin!



回答7:

Below code will work for any screen size.

div.centered {
   background-color: rgb(18, 80, 144);
   height: 100vh;
}
div.centered span {
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%,-50%);
   color: rgb(250, 255, 255);
}
<div class="centered">
	<span>Center</span>
</div>