简体   繁体   English

将div水平居中并留有空白(CSS)

[英]Center div horizontally with margin (CSS)

How can I center horizontally a div which has margin? 如何才能水平对齐具有边距的div?

<div id="container">
    <div id="center_me"></div>
</div>


#container{
    position:relative;
    width:100%;
    height:400px;
}

#center_me{
    position:absolute;
    width:100%;
    margin:0 50px;
    max-width:300px;
    height:100%;
    left:50%;
    -webkit-transform:translateX(-50%);
}

I cant use margin:0 auto, as I want the div to have margin; 我不能使用margin:0 auto,因为我希望div具有margin; and the left:50% translateX(-50%) technique doesn't consider the margin. 而左:50%translationX(-50%)技术未考虑边距。 I want to preserve the margin fluidly (always center the div and always preserve the same fixed margin) as the window is resized. 我想在调整窗口大小时流畅地保留边距(始终将div居中并始终保留相同的固定边距)。 Am I missing something very obvious? 我是否缺少一些显而易见的东西?

http://jsfiddle.net/R3yny/ http://jsfiddle.net/R3yny/

Just Css,thanks. 只是CSS,谢谢。

By definition, if your element is offset from center with a margin it cannot be centered. 根据定义,如果您的元素偏离中心有边距,则无法居中。 What it sounds like you want to do it hold an element in a central-ish place on webpage with a responsive design. 听起来像您想做的那样,将元素放在具有响应式设计的网页中央位置。

The best way to get that done is to use margin widths as percentages, and eyeball your div until it looks like its about where you want it. 最好的方法是使用边距宽度作为百分比,并关注div,直到看起来像您想要的位置为止。 Check this sample out- it's really simple: 检查一下这个样本-这真的很简单:

http://codepen.io/staypuftman/pen/oHGAF http://codepen.io/staypuftman/pen/oHGAF

CSS: CSS:

.hero-text-area-container {
  background: #d6ffd1;
  float: left;
  margin: 0% 30%;
  padding-top: 20em;
  position: relative;
  width: 50%;
}

Is it possible, to simply have the margin on another div, that sits inside #center_me ? 是否可以仅在#center_me内的另一个div上#center_me

<div id="container">
    <div id="center_me">
        <div id="i_have_the_margin"></div>
    </div>
</div>

Then you can use margin:0 auto; 然后您可以使用margin:0 auto; on #center_me , like this - http://jsfiddle.net/nickg1/R3yny/3/ (Tested in Opera) #center_me ,像这样#center_me : //jsfiddle.net/nickg1/R3yny/3/ (在Opera中测试)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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