我有一个div应该是全宽(它有一个应该跨越整个页面的背景图像),我希望内容具有固定的宽度并且居中。
有没有办法做到这一点,没有centered-content
div:
<div class="background">
<div class="centered-content">My content</div>
</div>
这就是我想要实现的目标(只有一个 div):
编辑:我不希望文本居中。我想要一个400px
宽中心文本框,其中包含左对齐文本。
答案 0 :(得分:2)
原来是这个问题的解决方案,我刚想通了。
您可以使用calc()
设置填充。不幸的是,它涉及一个部门,即not properly supported by android。
#container {
background: rgba(0, 255, 0, 0.1);
padding: 6em calc((100% - 400px)/2);
}
<div id="container">
One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin.<br>
He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches into stiff sections. The bedding was hardly able to cover it and seemed ready to slide off any moment.<br>
His many legs, pitifully thin compared with the size of the rest of him, waved about helplessly as he looked. "What's happened to me? " he thought. It wasn't a dream. His room, a proper human room although a little too small, lay peacefully between its four familiar walls.<br>
A collection of textile samples lay spread out on the table - Samsa was a travelling salesman - and above it there hung a picture that he had recently cut out of an illustrated magazine and housed in a nice, gilded frame. It showed a lady fitted out with a fur hat and fur boa who sat upright, raising a heavy fur muff that covered the whole of her lower arm towards the viewer. Gregor then turned to look out the window at the dull weather. Drops<br>
</div>
答案 1 :(得分:0)
最简单的解决方案是添加到class="centered-content"
margin: 0 auto;
<div class="background">
<div class="centered-content">My content</div>
</div>
* {
margin: 0;
padding: 0;
}
.background {
width: 100%;
background: #ddd;
}
.centered-content {
width: 600px;
margin: 0 auto;
height: 400px;
background: #c01;
}
答案 2 :(得分:-1)
你想摆脱centered-content
div,仍然以固定的宽度居中HTML?这是不可能实现的,您可以将背景图像设置为正文,这样您就可以摆脱.background
div,但只有一个div具有全宽背景,但也以固定宽度居中,是不可能的。
当然你可以用jQuery解决这个问题,这里有一个例子:
$(document).ready(function() {
fixedWidth = 800;
padding = ($(window).width() - fixedWidth) / 2;
$(".background").css({paddingLeft: padding+"px", paddingRight: padding+"px"});
});
请注意,此代码未经测试,您可能需要更改内容。您还需要使用$(window).resize()
函数来捕捉屏幕宽度的变化,因为每次宽度变化时都必须更新填充。