ShellRox ShellRox - 1 year ago 63
CSS Question

Automatic margin doesn't center elements in div

Lately I was creating a searchbox for my website, but I wanted it to be constantly centered in every y and x dimension.

I have div container


.searchbox {
position: absolute;
text-align: center;
width: 100%;
left: 0%;
top: 55px;
height: 115px;
background-color: black;

container, I made special

.mover {
margin: 0 auto;
width: 50%;

As you see width is 50% because I thought it would center it, but it didn't, and margin is automatic, which I don't think even works without 50% width.

Full code and Result.

I think my style is kinda messed up and there are useless things which may affect automatic margin.
What may the problem be? does
margin: auto;
doesn't work with current position of div? What do I need to change? If not, what's the problem?

I will be very thankful if you upload solution on my current fiddle.

Answer Source

your class has a specified width in px which is larger than the container.

.search {
    width: 100%;/*changed this line*/
    height: 35px;
    margin-top: 20px;
    margin-left: 0 auto;
    margin-right: 0 auto;
    border: solid 1px black;
    border-radius: 7px;

However using percentages can lead to un predictable layouts when viewed on different screen resolutions.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download