我观察到text-align: center
,同时在容器块元素边界(在本例中为div
)的文本左右两侧创建相等的空间,同时也将文本的对齐方式更改为{ {1}}。在此,它违反了单一责任主体。
使用center
text-align: center
div {
box-sizing: border-box;
width: 600px;
height: 500px;
border: 4px solid red;
padding: 0 150px 0 150px;
display: table-cell;
vertical-align: middle;
text-align: center;
}
随意读者需要注意的一些事项:
我不是问如何垂直对齐文字。
我知道如果我在<div>This is a long piece of text that runs into many lines of reading. Some people like to sleep, and some like to drink water. This is looking like a poem. It is even aligned like one. What a pity!</div>
内取div
,我可以做我想做的事。我不是要求我试图解决的问题的替代解决方案。我问是否有办法做到这一点,而不是采取一个kludge,如采取包含div
。
使用kludge:在div内部使用div
div
body > div {
box-sizing: border-box;
width: 600px;
height: 500px;
border: 4px solid red;
display: table-cell;
vertical-align: middle;
padding: 0 150px 0 150px;
}
div > div {
text-align: justify;
margin: 0 auto;
}
我想知道是否有办法在包含块(如div)中水平居中文本,同时将文本对齐保留为<div>
<div>This is a long piece of text that runs into many lines of reading. Some people like to sleep, and some like to drink water. This is NOT looking like a poem. Oh, so nice! But it uses a hack, what the fack!</div>
<div>
或left
。
答案 0 :(得分:1)
不,没有,并且有充分的理由。因为如果在CSS引擎本身内有一个这样的内置解决方案,而没有你设置填充,谁将决定文本内容必须有多宽?
你最好的选择就是做你已经做过的事情。也就是说,要在左侧和右侧设置填充,并保留left
(或padding
,请您选择)。这将完全符合您的要求。
您正在考虑的方法的问题是您需要以某种方式定义居中文本应该有多宽。在您的示例中,您设置了width
和div
,并通过隐式设置中间文本的剩余宽度。
确保某些东西只在容器中使用预定义的唯一真正的解决方案实际上是为它创建一个DOM元素。这意味着,如果您不想使用padding
/ width
hack,则可能无法避免额外 protected override void OnEndRequest(object sender, EventArgs args)
{
var reqSsl = FederatedAuthentication.SessionAuthenticationModule.CookieHandler.RequireSsl;
//System.IdentityModel.Services.ChunkedCookieHandler
if (reqSsl)
{
FederatedAuthentication.SessionAuthenticationModule.CookieHandler.RequireSsl = false;
try
{
base.OnEndRequest(sender, args);
}
finally
{
FederatedAuthentication.SessionAuthenticationModule.CookieHandler.RequireSsl = reqSsl;
}
}
else
base.OnEndRequest(sender, args);
}
。