Html 如何将 div 浮动到中心?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4982280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 06:41:59  来源:igfitidea点击:

How do i float a div to the center?

htmlcssxhtml

提问by Eli Reznekervitz

I want to be able to center a div in the middle of a page but can't get it to work. I tried float: center; in css but it doesn't seem to work.

我希望能够在页面中间居中一个 div,但无法让它工作。我试过 float: center; 在 css 中,但它似乎不起作用。

回答by Drew Bartlett

There is no float: center; in css. Use margin: 0 auto; instead. So like this:

没有浮动:中心;在 CSS 中。使用保证金:0 自动;反而。所以像这样:

.mydivclass {
    margin: 0 auto;
 }

回答by Hussein

You can do it inline like this

你可以像这样内联

<div style="margin:0px auto"></div>

or you can do it via class

或者你可以通过课堂来完成

<div class="x"><div>

in your css file or between <style></style>add this .x{margin:0px auto}

在您的 css 文件中或在<style></style>添加此文件之间.x{margin:0px auto}

or you can simply use the center tag

或者你可以简单地使用中心标签

  <center>
    <div></div>
  </center>

or if you using absolute position, you can do

或者如果你使用绝对位置,你可以做

.x{
   width: 140px;
   position: absolute;
   top: 0px;
   left: 50%;
   margin-left: -70px; /*half the size of width*/
}

回答by Elbert Alias

Try margin: 0 auto, the div will need a fixed with.

尝试margin: 0 auto,div 将需要一个固定的。

回答by Stanley Amos

if you are using widthand height, you should try margin-right: 45%;... it is 100% working for me.. so i can take it to anywhere with percentage!

如果你正在使用widthand height,你应该尝试margin-right: 45%;......它对我来说是 100% 的工作......所以我可以把它带到任何地方!

回答by iAnuj

Give the DIV a specific with in percentage or pixels and center it using CSS margin property.

为 DIV 指定一个特定的百分比或像素,并使用 CSS 边距属性将其居中。

HTML

HTML

<div id="my-main-div"></div>

CSS

CSS

#my-main-div { margin: 0 auto; }

enjoy :)

请享用 :)

回答by SimeriaIonut

If for some reason you have position absolute on the div, do this:

如果由于某种原因您在 div 上有绝对位置,请执行以下操作:

<div class="something"></div>

.something {
    position:absolute;
    left:0;
    right:0;
    margin-left:auto;
    margin-right:auto;
}

回答by Indra

Simple solution:

简单的解决方案:

<style>
.center {
    margin: auto;

}
</style>

<div class="center">
    <p> somthing goes here </p>
</div>

Try Online

在线试用