如何让所有页面内容通过CSS水平居中? [英] How to get all page content to center horizontally via CSS?

查看:130
本文介绍了如何让所有页面内容通过CSS水平居中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了让我的页面上的内容水平居中(它正在拥抱左角),我添加了这个CSS:



In an attempt to get content on my page to center horizontally (it was hugging the left corner), I added this CSS:

body {
    width:80%;
    margin-left:auto;
    margin-right:auto;
}





通过在页面左侧添加一些边距(死区)来改善问题,但是内容仍然是以左为中心的。我怎样才能让内容真正居中,而不是只是不情愿地向右移动?



This improves matters by adding some margin ("dead space") on the left of the page, but the content is still left-centric. How can I get the content to really center, rather than just begrudgingly move a little to the right?

推荐答案

这是给你的提示:这个技巧将元素集中在一起,不是元素的孩子。这对于 div 是有意义的,而不是对于身体。

假设你想要放一首诗。它要求strophes一如既往地左对齐,但是你需要在strophes周围创建一个边界列,并且该列应该在左右两侧具有相等的边距。由于您不知道可用空间有多大,因此您需要使用auto。对于宽度由其内容定义的元素是有意义的。



您需要做一个重要步骤:停止混合元素和元素内容。



我不知道你期望在页面上做什么,但也许你需要的是左边一些固定的填充和对,最好是相对的单位,而不是绝对像素。







另一个方法是:

Here is the hint for you: this trick centers the element, not children of element. It makes sense for div, and not for body.
Let's say you want to place a poem. It requires that the strophes was left-aligned, as always, but you need to create a bounding column around the strophes, and the column should have equal margins on left and right. As you don't know how much space is available and required, you use auto. It makes sense for the element which width is defined by its content.

You need to do one important step: stop mixing up elements and content of elements.

I have no idea what would you expect doing it on page, but perhaps all you need is some fixed padding on left and right, better be in relative em units, not absolute pixels.



Another approach would be:
<html>
   <head>
      <style>
         div.body {
            width: 80%;
            margin-left:auto;
            margin-right:auto;
         }
      </style>
   </head>
<body>

<div class="body">
Put here what used to be your page's content
</div>

</body>
</html>



你明白了吗?它确实有效,但我没有看到很多实际意义。相信我,只需使用一些3em用于 margin-left margin-right



-SA


页面 body 基本上是一个包含页面的矩形。

你的css只是说这个矩形是浏览器窗口宽度的80%,它是水平居中的。

你瞄准了错误的目标。



你需要将居中应用于页面的每个元素。

如果你使用paragraphes,你需要这样的东西:

The page body is basically a rectangle which contains your page.
Your css simply says that this rectangle is 80% of browser window width and that it is centred horizontally.
You aim the wrong target.

You need to apply the centring to each element of the page.
If you use paragraphes, you need something like:
p {
    text-align:center;
}


这篇关于如何让所有页面内容通过CSS水平居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆