简体   繁体   中英

Making a div slightly off-center

Usually I would do this by either setting the margin to auto, using position:absolute, or via padding but unfortunately these will not work in this case. I need a div to be about 15 pixels off-center horizontally from the page. The tricky bit is it needs to scale correctly as the page widens. It seems to me that I would need to do this horizontal adjustment based on the center point, rather than the left hand side. How could I achieve this? Thanks.

Use a container div, which is centered, then its content you can give margin-left:npx - like so:

HTML

<div id="container">
    <span id="green">&nbsp;</span><br />
    <span id="blue">&nbsp;</span>
</div>

CSS

#container{width:100px; margin:auto auto; background-color:red;}
#container span{display:block; width:100%; }
#green{background-color:green; margin-left:10px;}
#blue{background-color:blue; margin-left:-10px;}

See the example coded up here - http://jsfiddle.net/Xpk8A/1/

give a wrapper with: margin: auto; position: absolute;

inside wrapper, put div: position:relative; left: -15px; (or whatever you want)

example page would help.

You can absolutely position your div and set the left attribute to 50%. Then, set the margin-left to 50% + 5px (whatever that is). This would only work if you have a fixed width on the box, however. For example, if the box is 200px wide, the margin-left would be -115px .

The key is to set width:100% and a fixed margin , as you can see in my example below

<style>
div {
background-color:red;
 height:100px;
margin:0 auto;
width:100%;
margin-left:15px;
}
</style>

<div></div>
<html>
    <body>
        <div class="centered">
            <div class="offcenter">
            </div>
        </div>
    </body>
</html>

The css will be:

.centered
{
    margin: 0 auto;
    width:300px;
    height:200px;
    background-color:red;
}

.offcenter
{
    background-color:blue;
    width:285px;
    height:inherit;
    float:right;
}

http://jsfiddle.net/evbbq/

You can use display:inline-block for center the DIV then give your margin to it .

Like this:

.Parent{text-align:center;}
.Child{
    display:inline-block;
    text-align:left;
    width:200px;
    height:150px;
    background:red;
    margin-left:15px;
}

Check this fiddle http://jsfiddle.net/Xpk8A/2/

Remove margin-left:15px then click on Run button in the fiddle to see the different.

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