Shafizadeh
Shafizadeh

Reputation: 10350

How to make element center (horizontally) with fixed position when there is min-width?

I have following codes:

div{
	position: fixed;
	border: solid 1px #aaa;
	top: 20px;
	right: 50%;
	margin-right: -20%;
	width: 40%;
	min-width: 250px;
	text-align: center;
}
<div> This element should be center (horizontally) in all screen-sizes </div>

<div> (in the code above) is center when its width is more than 250px. But when I decrease the size of screen and min-width: 250px; executes, then it is not center anymore.

How can I keep it center in all-screen-sizes?

Note: (legacy browser support) crossing browsers is important for me.

Upvotes: 2

Views: 75

Answers (3)

Shafizadeh
Shafizadeh

Reputation: 10350

The best way:

div{
    position: fixed;
    border: solid 1px #aaa;
    top: 20px;
    right: 0;
    left: 0;
    margin-right: auto;
    margin-left: auto;
    width: 40%;
    min-width: 250px;
    text-align: center;
}
<div> This element should be center (horizontally) in all screen-sizes </div>

Upvotes: 1

Leo The Four
Leo The Four

Reputation: 699

you have to use margin:auto; property. Simply set the width of the div with percentage and set the margin to auto and it will be automatically center positioned when re-sizing the window.

if you want to keep your div fixed then you can simply use percentage in margin.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style>
    .fixedCenter {height:200px;
                    width:60%;
                    background-color:green;
                    position:fixed;
                    margin:10px 20%;}
</style>
</head>

<body>
    <div class="fixedCenter">


    </div> 
</body>
</html>

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122087

You can use left: 50% and transform: translate(-50%, 0);

div{
  position: fixed;
  border: solid 1px #aaa;
  top: 20px;
  width: 40%;
  min-width: 250px;
  text-align: center;
  left: 50%;
  transform: translate(-50%, 0);
}
<div> This element should be center (horizontally) at all screen-sizes </div>

Or you can use JQuery

$(window).on("resize", function () {
  var half = $('div').width()/2;
  $('div').css('margin-left', -half);
}).resize();
div{
  position: fixed;
  border: solid 1px #aaa;
  top: 20px;
  width: 40%;
  min-width: 250px;
  text-align: center;
  left: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div> This element should be center (horizontally) at all screen-sizes </div>

Upvotes: 2

Related Questions