Search code examples
htmlcsscenterfixed

Centering a <div>


Good evening,

I am trying to center a 'Contact Details' div. I used the below code however after using position: fixed it doesn't look like it's centered. Is there another way to have it centered perfectly while using position:fixed? I would like to keep the div centered while one scrolls up and down. Any help will be appreciated, thanks!

.secondary {
	height: 350px;
	width: 400px;
	background-color: #ccc;
	box-shadow: 5px 5px 5px #000;
	margin-top: 200px;
	position: fixed;
	margin-left: 40%;
}
<section class="secondary">
	<h3>Contact Details</h3>
	  <ul class="contact-info">
	    <li class="phone"><a href="tel:###-###-####">###-###-####</a></li>
		<li class="mail"><a href="mailto:e************@gmail.com"             target="_blank">e************@gmail.com</a></li>
		<li class="twitter"><a href="http://twitter.com/intent/tweet?screen_name=ec#######" target="_blank">@ec*******</a></li>
		<li class="linkedin"><a href="http://linkedin.com/in/e####-######-8a791988" target="_blank">Edwin Castro</a></li>
	</ul>
</section>


Solution

  • Since you're using fixed dimensions for your div rather than making it responsive you could use:

    .secondary {
        height: 350px;
        width: 400px;
        background-color: #ccc;
        box-shadow: 5px 5px 5px #000;
        position: fixed;
        margin-left: -200px;
        margin-top: -175px;
        left: 50%;
        top: 50%;
    }
    

    All it does is move the element to the center then use a negative margin to pull it back by half its total width/height leaving it perfectly centered.

    This feels like quite an outdated approach though. If you did wish to make this responsive instead you could try something like:

    .secondary {
        height: 350px;
        width: 100%;
        max-width: 400px;
        background-color: #ccc;
        box-shadow: 5px 5px 5px #000;
        position: fixed;
        left: 50%;
        top: 50%;
        -webkit-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
    }
    

    It may not give you the precise styling you're looking for but it'll put you on the right path.