简体   繁体   English

在页面上将Div元素居中?

[英]Center a Div element on the page?

I was looking everywhere over the internet for the past 40 mins of trying to figure out how to properly center a div element. 在过去的40分钟里,我一直在Internet上四处寻找,试图弄清楚如何正确地将div元素居中。

Here is a snippet of my code of what I want centered: 这是我要居中的代码片段:

<div id="boxcenter">
            <div id="boxoutline">
                <div id="boxmodel">
                    <p>Cupcake ipsum dolor. Sit amet sweet tiramisu sweet muffin caramels. I love lollipop sweet sweet roll fruitcake dragée.
                    Halvah tootsie roll cookie chocolate cake fruitcake sesame snaps I love I love. Chupa chups gummies I love marshmallow jelly donut powder 
                    dragée danish. Gummies I love fruitcake sweet croissant unerdwear.com dessert chocolate cake pastry.
                    Gummi bears marshmallow I love bonbon. Soufflé liquorice chocolate bar applicake marzipan sweet cake I love pie. Fruitcake 
                    wafer brownie halvah muffin muffin. Gingerbread gingerbread macaroon jelly beans icing soufflé donut marzipan candy canes.
                    </p>
                </div>
            </div>
        </div>

Here is the css I am using to create the box model and to center it. 这是我用来创建盒子模型并将其居中的CSS。 To center the box model I created I am using the div id of "boxcenter". 为了使我创建的盒子模型居中,我使用了“ boxcenter”的div ID。 The goal is to center this bad boy on the top of the page. 目标是将这个坏男孩放在页面顶部。

/*BOX MODEL STYLE*/
#boxmodel p{
    border: 2px dashed; 
}

#boxmodel{
    padding: 10px 20px;
    border: 15px solid green;
    margin: 20px;   
    height: 150px;
    width: 700px;   
}

#boxoutline{
    border: 2px dashed;
    width: 810px;
}

#boxcenter{
    position: fixed;
    top: 0px;
    margin: 0 auto;

}

Unfortunately all it is doing is displaying the box model on the top right of the page, not entirely too sure of how to correct this of how to center it on the page itself...Any ideas? 不幸的是,它所做的只是在页面的右上方显示框模型,而不是完全确定如何更正此问题,以及如何将其置于页面本身的中心...任何想法?

Must set the width and remove position:fixed 必须设置宽度并移除position:fixed

#boxcenter{
  width: 810px;
  margin: 0 auto;

}

Fiddle 小提琴

Use this css this will work fine for you 使用这个CSS这将适合您

DEMO HERE 此处演示

#boxcenter{
  width: 816px;
  margin: 0 auto;

}

Must set the width 必须设置宽度

#boxcenter {
  position: relative;
  width: 960px;
  margin: 0 auto;
}

but if you want position fixed then 但是如果你想固定位置

#boxcenter {
  position: fixed;
  width: 960px;
  top: 0;
  left: 50%;
  margin-left: -480px;   
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM