How to horizontally center a larger div of variable width, within a smaller div of variable width

前端 未结 2 950
醉梦人生
醉梦人生 2021-01-25 12:59

I want to achieve the following effect: http://jsfiddle.net/3KJta/1/

\"enter

Howev

相关标签:
2条回答
  • 2021-01-25 13:45

    If you are ok with using css3 and only support modern browsers you can use transform: translateX(-50%); to center the bigger box (currently supported browsers).

    See this example: http://jsfiddle.net/2SQ4S/1/

    0 讨论(0)
  • 2021-01-25 13:48

    If you use and extra element you can do it:

    <div class="small">
        <div class="smaller"></div>
        <div class="larger">
            <div>I'm extra</div>
        </div>
    </div>
    

    CSS

    .larger {
        position:relative; 
        left:50%;
        width:8000%;
        margin-left:-4000%;
        text-align:center;
        border:none;
    }
    .larger div {
        width: 200px;
        height: 200px;
        border-color: blue;
        margin:auto;
    }
    

    http://jsfiddle.net/3KJta/4/

    although that does cause some issues with content being wider than the page so you would need it all in a container with overflow:hidden:

    http://jsfiddle.net/3KJta/7/

    All a bit ugly though. Perhaps there's a solution where you can avoid doing this. Maybe a JS solution that measures the size of the content you're trying to show and offsets it.

    0 讨论(0)
提交回复
热议问题