简体   繁体   English

如何使用CSS将文本相对于其父div居中?

[英]How do I center text relative to its parent div with CSS?

I know I can use text-align: center; 我知道我可以使用text-align: center; on the parent div to center all its child elements, but what if I don't want all the child elements centered? 在父div上居中所有子元素,但是如果我不想让所有子元素居中呢? I just want, say, one child element centered relative to the parent. 我只想要一个相对于父母居中的子元素。

Say I have everything within a wrapper div. 假设我在包装器div中拥有所有内容。 Some headers, forms, etc. But at the bottom I want to center a small line of text crediting something. 一些标题,表单等。但在底部我想要一小部分文本中心。 How would I achieve that if its hierarchy is body > div.wrapper > div.credit? 如果它的层次结构是body> div.wrapper> div.credit,我将如何实现?

So why you are complicating the CSS here? 那么为什么你在这里复杂化CSS呢? Simply wrap that text in a div and use text-align: center; 只需将该文本包装在div中并使用text-align: center; for that particular div and you are done 对于那个特殊的div,你就完成了

And if you want to declare in a CSS hierarchy manner just use this 如果你想以CSS层次结构方式声明,只需使用它

body div:last-child {
   text-align: center;
}

Note: Be sure the text you want to be centered is the last div you are using else don't use last-child selector, better declare a class 注意:确保要居中的文本是您正在使用的最后一个div,否则不要使用last-child选择器,更好地声明一个类

Only specify which div to centre by saying which one: 只通过说出哪一个来指定哪个div居中:

div {
text-align:/* whatever align for the rest */
}

div:credit {
text-align:center;
}

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

相关问题 如何居中绝对定位的HTML块元素? (相对于其父代?) - How do I center an absolutely positioned HTML block element? (Relative to its parent?) 如何使用CSS在DIV中垂直居中放置文本? - How do I vertically center text in a DIV using CSS? CSS:当元素同级右对齐时,如何相对于其父元素居中? - CSS: How do I centre an element relative to its parent while right-aligning its sibling? 如何将div与位置相对居中,该位置也在css中显示表格单元格? - How do I center a div with position relative, which is also display table-cell in css? 如何相对于包含动态文本的父div定位div? - How do I position a div relative to the parent div which contains dynamic text? 如何使用 CSS 使文本居中,以便其中一个元素始终位于父元素的中心? - How do I center text with CSS so that one of the elements is always at the center of parent element? 如何阻止div从其父div继承CSS类? - How do i stop a div from inheriting the CSS class from its parent div? 使用 CSS 相对于另一个不是其父级的 div 定位一个 div - Position a div relative to another div which is not its parent using CSS 如何使用CSS在父div内水平居中放置4张图像的集合? - How do I horizontally center a set of 4 images inside a parent div with CSS? 如何将正文文本div居中? - How do I center the body text div?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM