Skip to content Skip to sidebar Skip to footer

Is It Possible To Center An Element That's Wider Than Its Parent And Absolutely Positioned Without Javascript?

BASE HTML/CSS - JSFiddle: https://jsfiddle.net/tae8pc1g/2/ All in the title really. All the important code in the JSFiddle is as follows:
Menu Bu

Solution 1:

Yes it is possible using:

1- For unknown width:

left: 50%;
transform: translateX(-50%);

2- For known width:

left: 50%;
margin-left: -(width/2)

Here a working JSFiddle to play with

body {
    text-align: center;
}

.example-button {
    position: relative;
    padding: 15px;
    border-radius: 5px;
    background: gray;
    display: inline-block;
    text-align: left;
}

.example-menu {
    position: absolute;
    display: inline-block;
    top: 100%;
    background: blue;
    margin:0;
    padding: 10px70px;
    list-style: none;
    left: 50%;
    -webkit-transform: translateX(-50%);
    transform: translateX(-50%);
}
<divclass="example-button">Menu Button
    <ulclass="example-menu"><li>Please</li><li>center</li><li>me!</li></ul></div>

Solution 2:

It may be considered a hack but using pure CSS you can put this on your example-button class :

left: 50%;
transform: translateX(-50%);

See https://jsfiddle.net/08fqfhum/

Note: this won't work on older browsers (IE8) since it uses CSS transforms. And for some browsers like Safari you would need to add a prefixed version of the transform property too :

-webkit-transform: translateX(-50%);

Post a Comment for "Is It Possible To Center An Element That's Wider Than Its Parent And Absolutely Positioned Without Javascript?"