css居中的几种方法_CSS居中的七种方法

css居中的几种方法

Centering HTML elements on a web page seems like it should be simple. In some cases, it is… but complex layouts often eliminate some solutions, leaving web developers working without a net.

在网页上将HTML元素居中似乎应该很简单。 在某些情况下是这样,但是复杂的布局通常会消除一些解决方案,从而使Web开发人员无需网络即可工作。

Centering elements horizontally on the page tends to be easiest, with vertical alignment harder to pull off, and combining the two the most difficult of all. In the age of responsive design, we rarely know the explicit height or width of elements, eliminating many possibilities. To my count, that leaves at least six centering methods in CSS. I’ll start from the simplest and best supported and move to the most complex, working from the same basic code:

在页面上水平居中往往是最容易的,垂直对齐更难实现,而将两者结合起来是最困难的。 在响应式设计时代,我们很少知道元素的明确高度或宽度,从而消除了许多可能性。 以我的观点,这在CSS中至少留下了六个居中方法。 我将从最简单,得到最佳支持的地方开始,然后从最基本的相同代码开始发展到最复杂的情​​况:

The shoe images will vary, but they will always have a native size of 500px × 500px. HSL colors are used for the backgrounds to keep a consistent color theme.

鞋子图片会有所不同,但它们的原始尺寸始终为500px×500px。 HSL颜色用于背景,以保持一致的颜色主题。

水平居中与文本对齐 (Horizontal centering with text-alignment)

css居中的几种方法_CSS居中的七种方法_第1张图片

Sometimes the obvious solution remains the best option:

有时,显而易见的解决方案仍然是最佳选择:

div.center {
	text-align: center;
	background: hsl(0, 100%, 97%);
}
div.center img {
	width: 33%; height: auto;
}

This doesn’t align the image vertically: you’d need to add padding to the

or margin-top and margin-bottom to its content to achieve that, leaving the container to gain its height from its content.

这不会使图像垂直对齐:您需要在

上添加padding或在其内容中添加margin-topmargin-bottom来实现此目的,而使容器从其内容中获取高度。

以边距居中:自动 (Centering with margin: auto)

css居中的几种方法_CSS居中的七种方法_第2张图片

Again primarily for horizontal centering, with the same limitations as the text-alignment method above:

再次主要用于水平居中,其限制与上述文本对齐方法相同:

div.center {
	background: hsl(60, 100%, 97%);
}
div.center img {
	display: block;
	width: 33%;
	height: auto;
	margin: 0 auto;
}

Note the display: block, necessary in this case for the image to accept margin: 0 auto.

请注意display: block ,在这种情况下,图像必须接受margin: 0 auto

表格单元居中 (table-cell centering)

css居中的几种方法_CSS居中的七种方法_第3张图片

Uses display: table-cell, rather than actual table markup; allows for both horizontal and vertical centering. Typically requires the addition and manipulation of a second, exterior element, which could be anything from a div to the body itself.

使用display: table-cell ,而不是实际的表标记; 允许水平和垂直居中。 通常需要添加和操纵第二个外部元素,该元素可以是从divbody本身的任何东西。

翻译自: https://thenewcode.com/723/Seven-Ways-of-Centering-With-CSS

css居中的几种方法

你可能感兴趣的:(css,html,python,js,javascript)