简体   繁体   中英

Centering div horizontally with large explicit width content is clipped

I need to center some content in a web page horizontally. The content may or may not have an explicit width.

I am using the stack overflow question centering a div block without the width as a model, and it works great when the content doesn't have an explicit width, or if the explicit width is smaller than the containing area.

However, if the width of the content is larger than the containing area, the content is still centered, but there is no way to scroll to the hidden content.

CSS:

.letterbox-outer-wrap {
    padding-top: 20px;
    position:relative;
    background: aqua;
    overflow:hidden;
}

.letterbox-outer-center {
    float:left;
    position:relative;
    left: 50%;
    background: yellow;   
}

.letterbox-inner-center {
    float: left;
    position:relative;
    left:-50%;
    background: red;
}

.letterbox-clear {
    clear: both;
}

.large-explicit-width {
    width: 3000px;
    background:purple;
}

HTML:

<div class="letterbox-outer-wrap">
    <div class="letterbox-outer-center">
        <div class="letterbox-inner-center">
            <p class="large-explicit-width">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            </p>
        </div>
    </div>
</div>

How can I center a div horizontally that may or may not have an explicit width? If the width is greater than the viewable container, I want to left align the content and let the browser place a scrollbar on the bottom of the screen (just like a normal web page).

Here's a jsfiddle example.

I can definitely use javascript and jQuery if needed.

When you use left property to center the content then you aren't able to access that with overflow, since you want to center when the width is less than browsers size and with your actual markup you can do some like this:

.letterbox-outer-wrap {
   text-align:center;
}
.letterbox-outer-center {
  display:inline-block;
}

Removing float and left properties you got this http://jsfiddle.net/s5TLz/1/

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM