Noy
Noy

Reputation: 116

Center div dynamically

I need to make a website and there is a button which is in the middle horizontally. I can use left 50% or margin-left but when I minimize the window - it isn't in the middle. How do I set the div to be exactly in the middle also when you minimize the window of the browser?

Edit: fixed it by doing as Trix said and adding

.center-div{
margin: 0 auto;

}

Upvotes: 0

Views: 3609

Answers (1)

Peyman Mohamadpour
Peyman Mohamadpour

Reputation: 17944

If your div has a width value, you may use:

CSS

.center-div{
    width: 100px;
    margin: 0 auto;
}

But, if not, you may add text-align: center to its parent and display: inline-block; to the centering div itself:

HTML

<div class="parent">
    <div class="center-div">
    </div>
</div>

CSS

.parent{
    text-align: center;
}
.parent .center-div{
    display: inline-block;
}

Upvotes: 2

Related Questions