С одной стороны, это может показаться немного странным, но на самом деле это работает без Javascript или сложных вычислений, поэтому я решил опубликовать его в любом случае.
Результат во фрагменте может выглядеть немного странно, потому что я сделал вкладки полупрозрачными, чтобы вы могли видеть, как они (не) взаимодействуют и лежат друг на друге.
Хитрость: поместите все элементы друг на друга, не используя абсолютную позицию, так что родительский элемент все равно автоматически увеличится, чтобы содержать его.Для этого я сделал следующие шаги:
- Отображение всех вкладок в виде встроенного блока, так что они в основном становятся строкой текста.
- Укажите, что эта строка не может переноситься (установив
white-space: nowrap
на родителя).Так как это также влияет на текст внутри вкладок, у меня было white-space: normal
, чтобы сбросить его. - Дайте каждому блоку правое поле -100%, заставляя их вести себя так, как если бы они были нулевой ширины относительно позиционированияследующего блока.То есть следующий блок будет начинаться с той же левой позиции.
- Некоторые детали, например, установка шрифта размером
0
на родительском элементе для устранения проблем с пробелами.Эту проблему также можно решить, удалив все пробелы между тегами div в HTML-коде.
Я добавил <p>
в каждую вкладку, чтобы поведение всех них было одинаковым ине допускать комментариев типа «Ey! Tab 2 начинается выше!»
Фактически требуется CSS довольно мало.Я разделил его, используя комментарии, так что вы можете легко удалить другие части.
И да, я сознательно сохранил имена rel
и abs
, потому что было слишком много работы для их рефакторингаи доказать, что лучше иметь описательные имена о цели (tab-container
, tab-sheet
), чем использовать имена, которые указывают на конкретные детали реализации.; -)
/* To make the basic alignment work */
.rel{
white-space: nowrap;
}
.abs{
vertical-align: top;
white-space: normal;
display: inline-block;
width:100%;
margin-right: -100%;
}
/* To solve the white-space issue, which would cause shifting of the tabs.
Can also be solved by removing white-space in HTML, in which case this
CSS is not needed. */
.rel{
font-size: 0;
}
.abs{
font-size: 1rem;
}
/* Additional styling, just for demo purposes */
.rel {
box-sizing: border-box;
border: 1px solid red;
}
.abs {
opacity: 0.5;
background: #eee;
box-sizing: border-box;
border: 1px solid blue;
}
.abs:nth-child(1) { color: red; }
.abs:nth-child(2) { color: grey; }
.abs:nth-child(4) { color: green; }
.abs:nth-child(5) { color: blue; font-weight: bold; }
<div class="rel">
<div class="abs intro"><p>First tab, all the way at the bottom and mostly invisible</p></div>
<div class="abs"><p>2</p></div>
<div class="abs"><p>3</p></div>
<div class="abs about-us">
<p>
When it comes to web design services, we are a top rated player with stunning capabilities that will immensely benefit every business. As we are a well experienced and highly skilled web design company, a lot of businesses bank on us for their affordable web design requirements. We provide a number of affordable web design packages and low cost web designing quotes for any of your requirements and preferences. Therefore a lot of businesses find it very convenient to work with us to avail of some profitable custom website design packages. Hence a huge customer base considers us the top web design company for small businesses.
WordPress is a highly popular platform for different kinds of web development projects. This open source platform provides a host of benefits to the designers and businesses. As a WordPress website development company we provide our clients with the complete suite of WordPress website development services. We are a top rated player among the long list of best WordPress companies in India. Our services are strongly backed by a team of accomplished and highly talented WordPress web designers. Call us to know the WordPress website design prices we offer. Take advantage of our unique capabilities on the WordPress platform and further your dreams of getting a stunning website.
We also have a strong presence in the Ecommerce Web Design Services segment. We are highly known for our unique capabilities to design responsive websites that can perform well on any user interface. We deliver highly creative design in every website design project we undertake for our clients. Along with web designing and ecommerce website design services, we also specialize in several other services that will benefit our customers in many ways. Our stunning capabilities in the field of business catalyst hosting have made us the number one Adobe Business Catalyst expert.
</p>
</div>
<div class="abs"><p>This is the last paragraph, which is actually on top..<p></div>
</div>
The proof is in the footer!