简体   繁体   English

保证金自动在简单的html / css代码中不起作用

[英]Margin auto not working in simple html/css code

As demonstrated here - http://jsfiddle.net/d4wUu/ , I could not get the red bordered box with the word "Testing" to center along the height of the black box containing it. 如此处所示-http: //jsfiddle.net/d4wUu/ ,我无法看到带有单词“ Testing”的带有红色边框的框沿包含它的黑框的高度居中。 It stays aligned to the top border of the black box, leaving some space below it. 它与黑框的顶部边框保持对齐,在其下方留有一些空间。

margin-top is not working either. margin-top也不起作用。 Any idea how I can get margin: auto or margin-top (with respect to the black box containing it) to work on the red bordered box here? 知道如何获得margin: automargin-top (相对于包含它的黑盒)可以在此处的红色边框上工作吗?

Fiddle 小提琴

add those: 添加这些:

display: table-cell;
vertical-align: middle;

to #heading . 前往#heading

There are a few ways to vertically center the element. 有几种方法可以使元素垂直居中。 As far as I know, margin: auto will not work vertically on the element unless you use some type of table/table-cell styling. 据我所知, margin: auto不能在元素上垂直工作,除非您使用某种类型的表/表单元格样式。

These additions to your CSS is one way to vertically center it: 这些对CSS的添加是垂直居中的一种方法:

#heading {  
    position:relative;
}
#heading-title {
    position:absolute;
    top: 50%;
    margin-top: -25px; /* this is half the height of the element */
}

Here's an updated fiddle show this working. 这是更新的小提琴,显示了此工作原理

Another workaround, 另一个解决方法

Give margin: 7px auto to #heading-title . margin: 7px auto #heading-title margin: 7px auto #heading-title margin: 7px auto

Here 7px because the height of the parent element is 65px and height of the child element is 50px. 此处为7px因为父元素的高度为65px,子元素的高度为50px。 There difference in height is 15px . 高度差为15px so, dividing the 15px between the margin-top and margin-bottom . 因此,将15px分隔在margin-topmargin-bottom

This technique can only be used if the height of the parent and child elements are fixed as it is in the OP's description above. 仅当父元素和子元素的高度固定不变时才可以使用此技术,就像上面OP中的描述一样。

Working Fiddle 工作小提琴

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

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