html/CSS how to make a div always center when the window is resized -


this question has answer here:

i have navigation bar want stay centered when window resized. bar on top of picture serves background of website. here's code:

<!doctype html>  <html lang="en">    <head>  	<style>  		body {  			font-family: trebuchet ms;  		}        	.containermain {  			margin: auto;  		}          .navibar {  			z-index: 1;  			position: absolute;  			background-color: #000000;  			border-radius: 5px;  			/*text-align: center;*/  			left: 200px;  			right: 80px;  			top:140px;  			width: 870px;  			/*max-width: 100%;*/  			margin: auto;  		}       </style>  </head>  <body style="margin:0px;">    	<div class="containermain">  		<img class="bg" src="bg.png" alt="background">  	</div>  	  	<div class="navibar">  			<a class="button btnhome" href="x.html#home" target="_blank">home</a>  			<a class="button" href="x.html#portfolio" target="_blank">portfolio</a>  			<a class="button" href="x.html#blog" target="_blank">blog</a>  			<a class="button" href="x.html#contact" target="_blank">contact</a>  	</div>   </body>   </html>

i've tried several approach "margin: auto", nothing works, navi bar pinned place. please help, in advance!

navbar fixed position because of position: absolute , left:200px & right: 80px values. try below snippet.

if want space on top, use margin-top: 140px

<!doctype html>  <html lang="en">    <head>    <style>      body {        font-family: trebuchet ms;      }      .containermain {        margin: auto;      }      .navibar {        z-index: 1;        background-color: #000000;        border-radius: 5px;        width: 870px;        margin: auto;      }    </style>  </head>    <body style="margin:0px;">      <div class="containermain">      <img class="bg" src="bg.png" alt="background">    </div>      <div class="navibar">      <a class="button btnhome" href="x.html#home" target="_blank">home</a>      <a class="button" href="x.html#portfolio" target="_blank">portfolio</a>      <a class="button" href="x.html#blog" target="_blank">blog</a>      <a class="button" href="x.html#contact" target="_blank">contact</a>    </div>  </body>    </html>


Comments