Center a position:fixed element
You basically need to set top
and left
to 50%
to center the left-top corner of the div. You also need to set the margin-top
and margin-left
to the negative half of the div's height and width to shift the center towards the middle of the div.
Thus, provided a <!DOCTYPE html>
(standards mode), this should do:
position: fixed;
width: 500px;
height: 200px;
top: 50%;
left: 50%;
margin-top: -100px; /* Negative half of height. */
margin-left: -250px; /* Negative half of width. */
Or, if you don't care about centering vertically and old browsers such as IE6/7, then you can instead also add left: 0
and right: 0
to the element having a margin-left
and margin-right
of auto
, so that the fixed positioned element having a fixed width knows where its left and right offsets start. In your case thus:
position: fixed;
width: 500px;
height: 200px;
margin: 5% auto; /* Will not center vertically and won't work in IE6/7. */
left: 0;
right: 0;
Again, this works only in IE8+ if you care about IE, and this centers only horizontally not vertically.
How to center elements in a fixed position element
No need for inner elements, you can use pseudo elements for this. For the centering, I use one of the most common and robust centering methods:
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
along with a positioned parent.
Here's what it looks like:
.note-add {
position: fixed;
background: rgb(189, 28, 175);
width: 75px;
height: 75px;
bottom: 0;
right: 50%;
border-radius: 50%;
margin-bottom: 30px;
}
.note-add::before,
.note-add::after {
content: "";
position: absolute;
background: red;
width: 30px;
height: 5px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.note-add::after {
transform: translate(-50%, -50%) rotate(90deg);
}
<div class="note-add"></div>
CSS horizontal centering of a fixed div?
left: 50%;
margin-left: -400px; /* Half of the width */
How do I horizontally center a fixed div while having the width fit the content inside
Remove margin-left
in code.
Set transform
and left
for horizontally center.
Modify width
to 100%.
.tab {
overflow: hidden;
background-color: #505050;
padding: 0;
width: 100%;
border-radius: 15px;
position: fixed;
top: 0;
z-index: 10;
transform: translateX(-50%);
left: 50%;
}
Related Topics
Css3 Nth of Type Restricted to Class
Bootstrap Navbar With Left, Center or Right Aligned Items
How to Center Floated Elements
Customizing Bootstrap CSS Template
Change Navbar Color in Twitter Bootstrap
How to Remove Focus Border (Outline) Around Text/Input Boxes - Chrome
Reset/Remove CSS Styles For Element Only
Using Regular Expression in Css
Css Selector That Applies to Elements With Two Classes
Border Gradient With Border Radius
Stretch and Scale a CSS Image in the Background - With CSS Only
Css Change Button Style After Click