2016-09-21 63 views
-1

我的HTML是如下:如何在div中居中div?

<div id="background_div"> 
    <img id="background_img" src="images/background.jpg" alt="dont matter"> 
    <i class="material-icons">perm_identity</i> 
    <div id="dropdown"> 
     <ul id="dropdown2" class="dropdown-content"> 
     <li><a href="#!">one<span class="badge">1</span></a></li> 
     <li><a href="#!">two<span class="new badge">1</span></a></li> 
     <li><a href="#!">three</a></li> 
     </ul> 
     <a class="btn dropdown-button" href="#!" data-activates="dropdown2">Select Service<i class="mdi-navigation-arrow-drop-down right"></i></a> 
    </div> 
    </div> 

我改变了语法有div ID为“background_div”(父/子)内的div id为“下拉”因为我认为它可以帮助我中心使用某种相对CSS功能。我最初有两个divs作为兄弟姐妹......基本上,我想要实现的是在background_div中获得下拉div。很高兴以一种快速响应的方式来做到这一点。

任何人都可以请提供一些CSS脚本来帮助我实现吗?

谢谢!

+0

你看,这里有一个很好的参考.. https://css-tricks.com/centering -css-complete-guide/ – choz

+0

你想要垂直还是水平居中? –

+0

@cup_of尝试垂直和水平居中。我使用父级div的文本对齐中心,但只是居中水平 - 垂直任何想法?欢呼! – ngboverflow

回答

0

这个CSS利用的Flexbox

#background_div { 
    display: flex; 
} 

#dropdown { 
    justify-content: center; 
} 
+0

小心这个。 Flexbox相对较新并且易受bug影响。在使用前研究您的浏览器支持。 –

+0

这是一个公平的警告,但Flexbox已经有一段时间了。此外,它在主流浏览器中也有很好的支持。对于这样的基本用例,无论如何,应该没有问题 – fvgs

0

您可以添加到text-align: center;#background_div CSS样式,但随后的#background_div内一切都会中心。如果你只希望某些部分为中心,环绕这些部件在<span>标签,与类centered,所以<span class="centered">。然后在你的CSS,加入

.centered { 
    text-align: center; 
} 

现在你可以添加各地要居中任何一个<span class="centered">

+0

非常感谢! – ngboverflow

0

我最喜欢的方法,以垂直居中的东西是要做到:

/* the div you want centered inside another div*/ 

#dropdown { 
    position: absolute; 
    top: 50%; 
    transform: translateY(-50%); 
} 

/* set the parent div to position relative */ 

#background_div { 
    position: relative; 
} 

这大概会弄乱你的水平中心,如果你正在使用文本对齐中心。在这种情况下它添加到你的CSS

width: 100px; /* give it any width that fits */) 
margin: 0 auto; 

所以您的最终代码如下:

#dropdown { 
    position: absolute; 
    top: 50%; 
    transform: translateY(-50%); 
    width: 100px; 
    margin: 0 auto; 
} 

#background_div { 
    position: relative; 
} 
+0

感谢您的详细信息! – ngboverflow

+0

np,是否为你工作? –

+0

嗨,有点(谢谢),但还有一些东西是错过的 - 使用物化框架,所以必须通过开发工具中的样式来找出行高和div高度是不同的 - 在我做同样的事情之后,所有的定位上面列出的代码工作!干杯 – ngboverflow