skip to Main Content

I have a grid with two columns. The first is a sidebar that the user can hide/show and the second is the main content. Here’s what that looks like…

sidebar shown
enter image description here

sidebar hidden
enter image description here

I would like to use CSS (tailwind, specifically) to horizontally center the main content iff the sidebar is hidden.

Code

<div className="w-full grid grid-cols-[auto_1fr]">
  <MySidebarComponent />
  <MyMainComponent />
</div>

Question

Is this possible / how can I make this work? I thought that tailwind’s new has variant might help, but I couldn’t get it to work.

Note

My sidebar has a property that changes based on its open/closed state. Note that this is based on Headless UI’s Disclosure component.

open state

<div data-headlessui-state="open">
  <div>Other contents here...</div>
</div>

closed state

<div data-headlessui-state></div>  // No contents

Playground

A place to tinker

2

Answers


  1. You can use tailwinds peer modifier, which also has support to style based on data attribute.

    <div className="w-full grid grid-cols-[auto_1fr]">
        <div className="border border-blue-500 peer" data-headlessui-state="open">Sidebar</div>
        <div className="border border-red-500 peer-data-[headlessui-state='open']:text-left text-center">Main content</div>
    </div>
    

    Here is a working example

    Login or Signup to reply.
  2. Here is a pure CSS solution that I did using the playground using a ‘Next-sibling combinator’ that selects the main content div if the state of side nav is "open".

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search