假设我有一个容器,并且我希望它在大屏幕上为1200px宽,而在<= 1200px的屏幕上,我希望它采用窗口的所有宽度。 问题是-哪种CSS语法是更好的做法,并且为什么?
1)
.container {
width: 1200px;
max-width: 100%;
}
<div class="container" style="border: 5px solid magenta; background-color: black; color: white; padding: 1em;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit, ea, nemo. Sequi saepe aut eius voluptatum doloribus! Aliquam corporis vitae eveniet, sapiente eos similique voluptatum molestiae, nostrum animi facere, voluptatibus nemo maxime voluptas ipsum atque! Molestias obcaecati totam pariatur vel.
</div>
2)
.container {
width: 100%;
max-width: 1200px;
}
<div class="container" style="border: 5px solid cyan; background-color: black; color: white; padding: 1em;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit, ea, nemo. Sequi saepe aut eius voluptatum doloribus! Aliquam corporis vitae eveniet, sapiente eos similique voluptatum molestiae, nostrum animi facere, voluptatibus nemo maxime voluptas ipsum atque! Molestias obcaecati totam pariatur vel.
</div>
我检查了各种浏览器和设备,两个CSS选项都工作良好。
答案 0 :(得分:0)
我会简单地使用它
.container {
max-width: 1200px;
}
<div class="container" style="border: 5px solid cyan; background-color: black; color: white; padding: 1em;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit, ea, nemo. Sequi saepe aut eius voluptatum doloribus! Aliquam corporis vitae eveniet, sapiente eos similique voluptatum molestiae, nostrum animi facere, voluptatibus nemo maxime voluptas ipsum
atque! Molestias obcaecati totam pariatur vel.
</div>
默认情况下,div
是块元素,因此无需指定width:100%
。它将像您实际遇到的那样简单地产生一些意外的问题,实际上是因为您忘记设置box-sizing:border-box
,因为设置了填充和边框,这会造成溢出。