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. It stays aligned to the top border of the black box, leaving some space below it.
margin-top
is not working either. 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?
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.
These additions to your CSS is one way to vertically center it:
#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
.
Here 7px
because the height of the parent element is 65px and height of the child element is 50px. There difference in height is 15px
. so, dividing the 15px
between the margin-top
and margin-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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.