Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center block element in element

I'm trying to center a block element (the WordPress caption box, including the image) but it won't work. I've tried:

.imagecenter {
   margin-left: auto;
   margin-right: auto;
   display: block;
}

But it just won't work. I've also tried margin-left: auto; margin-right: auto; but that won't work either. Is there anything I'm doing wrong? This is what the W3C documentation says I should do.

It looks like this in the HTML (to clarify):

<div id="content">
........post here......
<div class="wpcaption imagecenter" style="width:225px">
<img src="blah" />
Blah.
</div>
.........post here......
</div>

I have no control over the width of the element. It's set by the user. The user wants the div to be centered. It's not working. I've looked over documentation but it still won't work.

EDIT: I HAVE ALREADY TRIED MARGIN-LEFT: AUTO AND MARGIN-RIGHT: AUTO. IT DOESN'T WORK.

like image 281
Brandon Wang Avatar asked Jul 30 '09 15:07

Brandon Wang


People also ask

How do you center an element within another element?

Use the "inline-block" value of the display property to display the inner <div> as an inline element as well as a block. Set the text-align property on the outer <div> element to center the inner one. This property only works on inline elements.

What is the center of an element?

By definition, the center is the set of elements for which the conjugacy class of each element is the element itself; i.e., Cl(g) = {g}. The center is also the intersection of all the centralizers of each element of G.

How do you center align a block in HTML?

This tag has been deprecated in HTML 4 (and XHTML 1) in favor of the CSS text-align property, which can be applied to the <div> element or to an individual <p> . For centering blocks, use other CSS properties like margin-left and margin-right and set them to auto (or set margin to 0 auto ).

How do I center a div with a display block?

After setting the “display: block” property, we can make our image to block element. It can be centered using “margin: auto” property. Note: The body tag has been set to the “text-align: center” property. We know that it is not affecting the block elements.


Video Answer


1 Answers

In general, to position a div in the center, the technique is to make both the left and right margins auto and then give the div a width:

.centerDiv
{
    margin-left:auto;
    margin-right:auto;
    width: XXX px;
}
like image 122
Punit Vora Avatar answered Oct 11 '22 14:10

Punit Vora