Html 设置 div 宽度,对齐 div 中心和文本左对齐

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6952233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 09:54:28  来源:igfitidea点击:

Set a div width, align div center and text align left

htmlcss

提问by Alex

I have a small problem but I can't get it solved. I have a content header of 864px width, a background image repeated-y and footer image. Now I have this <div>over the background image and I want it to be like 855px width and the text align left but yet aligned center so it fits in the bg.

我有一个小问题,但我无法解决。我有一个 864px 宽度的内容标题,一个重复的背景图像和页脚图像。现在我<div>在背景图像上有这个,我希望它像 855px 宽度一样,文本左对齐但中心对齐,所以它适合 bg。

I once had it oke width some padding left but I figured out that was the correct padding for my screen resolution.

我曾经把它的宽度留有一些填充,但我发现这是我的屏幕分辨率的正确填充。

Soo briefly it is: Setting a div width - align the div center - align its text (content) left.

简单来说就是:设置 div 宽度 - 对齐 div 中心 - 将其文本(内容)左对齐。

回答by Stephen Wood

Set auto margins on the inner div:

在内部 div 上设置自动边距:

<div id="header" style="width:864px;">
    <div id="centered" style="margin: 0 auto; width:855px;"></div>
</div>

Alternatively, text align center the parent, and force text align left on the inner div:

或者,文本居中对齐父级,并强制文本在内部 div 上左对齐:

<div id="header" style="width:864px;text-align: center;">
    <div id="centered" style="text-align: left; width:855px;"></div>
</div>

回答by Kleber S.

Try:

尝试:

#your_div_id {
  width: 855px;
  margin:0 auto;
  text-align: center;
}

回答by nikc.org

Use auto margins.

使用自动边距。

div {
   margin-left: auto;
   margin-right: auto;
   width: NNNpx;

   /* NOTE: Only works for non-floated block elements */
   display: block;
   float: none;
}

Further reading at SimpleBits CSS Centering 101

进一步阅读SimpleBits CSS Centering 101

回答by Stephen

All of these answers should suffice. However if you don't have a defined width, auto margins will not work.

所有这些答案都应该足够了。但是,如果您没有定义宽度,自动边距将不起作用。

I have found this nifty little trick to centre some of the more stubborn elements (Particularly images).

我发现了这个漂亮的小技巧来集中一些更顽固的元素(特别是图像)。

.div {
   position: absolute;
   left: 0;
   right: 0;
   margin-left: 0;
   margin-right: 0;
}