So, I just discovered this today and I couldn't find it this solution anywhere on Stackoverflow, so I thought I'd share it. Let me know if it's been posted somewhere else and I'll mark it as duplicate.
As far as I know centering an element wider than it's parent is a fairly common problem, the only solutions I've come across make use of Javascript, which turns out as a lengthy, messy bit of code that's annoying to maintain across lots of elements using this functionality.
The problem HTML:
<div class="container-fluid" >
<div class="center-me-fixed">
<span> Center </span>
</div>
</div>
CSS:
.container-fluid {
max-width: 400px;
width: 100%;
height: 100%;
display:block;
margin:auto;
}
.center-me-fixed {
width: 500px;
height:50px;
text-align: center;
}
The solution:
Use absolute positioning on the child you need to center, mess with the left/right values and set margin to auto like so:
CSS:
.center-me-fixed {
position:absolute;
left: -1000%;
right: -1000%;
margin: auto;
display: block;
width: 500px;
height: 50px;
}
Make sure the parent's container position is relative:
.container-fluid {
position: relative;
width: 100%;
height: 100%;
display:block;
margin:auto;
}
And that's it! I'm not sure how this works, if someone could explain that would be cool.
I searched on the web and the best solutions i've found is this
Fiddle
css:
html, body {
height: 100%;
}
div.container-fluid {
border:1px solid blue;
max-width:400px;
margin:0px auto;
min-height: 100%;
}
div.container-fluid .center-me-fixed {
position:relative;
right:50%;
text-align:center;
}
div.container-fluid .center-me-fixed span {
border:1px solid green;
width: 500px;
height:50px;
display:inline-block;
margin-right:-100%;
}
html:
<div class="container-fluid">
<div class="center-me-fixed">
<span>
this should be centered
</span>
</div>
</div>
If this solution does not suit your needs, i apologize for making you lose time.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.