简体   繁体   English

如何在容器内的div中将div居中?

[英]How can I center a div inside a div within a container?

I'm using the Materialize CSS front end framework and using margin: 0 auto; 我正在使用Materialize CSS前端框架并使用margin:0 auto; as I always have, and having a nightmare getting this div centered within its parent. 一如既往,噩梦让这个div集中在其父对象中。 What gives? 是什么赋予了?

 .outer { border: 1px solid red; height:100px; } .inner{ border: 1px solid black; height:50px; margin: 0px auto; } 
 <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/css/materialize.min.css"> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/js/materialize.min.js"></script> <div class="container"> <div class="row outer"> <div class="col l6 inner"> </div> </div> </div> 

http://codepen.io/kinsdotnet/pen/mEYJVg http://codepen.io/kinsdotnet/pen/mEYJVg

Materialise uses a grid system that floats elements. 物化使用浮动元素的网格系统。 You can't use margin: auto on a floated element. 您不能使用margin: auto对浮动元素使用margin: auto

You'll need to either use offset classes form the grid, or rearrange the grid and that child element... 您将需要使用偏移类形成网格,或者重新排列网格和该子元素...

( http://codepen.io/jmsherry/pen/OXYVRL <-- like that) http://codepen.io/jmsherry/pen/OXYVRL <-那样)

Also, don't listen to the really bad advice of !important and Absolute positioning. 另外,不要听从!重要和绝对定位的错误建议。 There are better ways to do this... 有更好的方法可以做到这一点...

Absolute inside Relative 绝对内在相对

Set the position of the outer div to relative, the inner to absolute. 将外部div的位置设置为相对,将内部的位置设置为绝对。

To make margin: 0px auto work, add left: 0; right:0; 要使margin: 0px auto工作,请left: 0; right:0;添加left: 0; right:0; left: 0; right:0;

Also you must specify width to the inner div. 另外,您必须指定内部div的宽度。

if you want to center vertically, 如果您想垂直居中,

just replace: 只需替换:

margin: 0px auto

with: 与:

margin: auto

Result: 结果:

 .outer { border: 1px solid red; height:100px; position:relative; } .inner{ border: 1px solid black; height:50px; margin: 0px auto; width:100px; position:absolute; left:0; right:0; } 
 <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/css/materialize.min.css"> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/js/materialize.min.js"></script> <div class="container"> <div class="row outer"> <div class="col l6 inner"> </div> </div> </div> 

Try adding this to your inner class: 尝试将其添加到内部类中:

float:none !important;

it looks like the class col applies a float left, and that's why it doesn't center 它看起来像类col向左浮动,这就是为什么它不居中的原因

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

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